-1

My project contains code of JAVA & KOTLIN both, I have only one activity(Main) where many fragments are placed in a container. I want to work on composable screen which would be invoked in java code and should work as a fragment.

I want to do something like this(to invoke my screen) in JAVA file:

FragmentTransaction fragmentTransaction = manager.beginTransaction();
                fragmentTransaction.replace(R.id.container, MyCompose, tag);

And MyCompos would be a screen/listing made with composable. e.g

@Composable
fun makeText(){
// my custom view
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45

1 Answers1

1

I'd like to explain it in two steps.

Firstly you need to add a composable view to your fragment XML file.

 <androidx.compose.ui.platform.ComposeView
    android:id="@+id/compose_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Secondly, you need to define your composable to your XML composable component. (I recommended using view binding to handle this situation easily.Btw sorry for kotlin answer if you want it as a Java)

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
): View {
        _binding = FragmentExampleBinding.inflate(inflater, container, false)
        val view = binding.root
        binding.composeView.apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                // In Compose world
                MaterialTheme {
                    Text("Hello Compose!")
                }
            }
        }
        return view
    }
Enes Zor
  • 973
  • 8
  • 14