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

1

5

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://mcmap.net/q/327239/-android-jetpack-compose-and-xml-in-activity

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?

Indiscipline answered 12/11, 2023 at 13:29 Comment(0)
C
7

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 your 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
  }
)
Clothesline answered 15/11, 2023 at 19:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.