Is it possible to use both Android jetpack Compose views and xml files together in same Activity?

975 Views Asked by At

I am facing an issue in my Android app where I'm unable to use supportFragmentManager in my ComponentActivity subclass. As per my understanding, ComponentActivity does not support the FragmentManager out of the box. And if I want to use supportFragmentManager Activity should be subclasses of AppCompatActivity or FragmentActivity. However, I'm encountering a problem where it seems to be unavailable. I want to use both JetPack Compose and XML in my class,

I have followed this https://stackoverflow.com/a/65653754/3467187

class AbcActivity : ComponentActivity(n) {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_permissio)
    if (savedInstanceState == null) {
         // Here I want to use supposrtFragmentManger
    }
}

}

Gradle file look like this,

dependencies {

implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2")
implementation("androidx.activity:activity-compose:1.8.0")
..
}

Any idea to use both JetPack Compose and XML in same class in a way I could use fragment Manager?

2

There are 2 best solutions below

0
ItzDavi On

Yes, you can use Compose in your XMLs and also the other way around.

From this answer.

Method 1

1. Add ComposeView to you XML

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

2. Set the content from you activity

findViewById<ComposeView>(R.id.my_composable).setContent {
    MaterialTheme {
        Surface {
          Text(text = "Hello!")
        }
    }
}

Method 2

You can use AndroidViewBinding.

Before jumping on with this method, read this

@Composable
fun AndroidViewBindingExample() {
    AndroidViewBinding(ExampleLayoutBinding::inflate) {
        exampleView.setBackgroundColor(Color.GRAY)
    }
}

XML in Compose

AndroidView(
    factory = { context ->
        val view = LayoutInflater.from(context).inflate(R.layout.my_layout, null, false)
        val textView = view.findViewById<TextView>(R.id.text)

        // do whatever you want...
        view // return the view
      },
    update = { view ->
    // Update the view
  }
)
0
AnumShafiq On

Yes, it is possible and easy. I have found it as a requirement and implemented it myself. You can go through the article to understand. https://medium.com/p/51662a94c552