我在 Android 应用程序中遇到一个问题,无法在我的 ComponentActivity 子类中使用 supportFragmentManager。据我了解,ComponentActivity 不支持开箱即用的 FragmentManager。如果我想使用 supportFragmentManager Activity 应该是 AppCompatActivity 或 FragmentActivity 的子类。但是,我遇到了一个似乎不可用的问题。 我想在我的课堂上同时使用 JetPack Compose 和 XML,
我已经关注了这个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 文件看起来像这样,
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")
..
}
有没有办法在同一个类中同时使用 JetPack Compose 和 XML,就像我可以使用片段管理器一样?
是的,您可以在 XML 中使用 Compose,反之亦然。
来自这个答案。
ComposeView
添加到您的 XML<androidx.compose.ui.platform.ComposeView
android:id="@+id/my_composable"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
findViewById<ComposeView>(R.id.my_composable).setContent {
MaterialTheme {
Surface {
Text(text = "Hello!")
}
}
}
您可以使用
AndroidViewBinding
。
在继续使用此方法之前,请阅读this
@Composable
fun AndroidViewBindingExample() {
AndroidViewBinding(ExampleLayoutBinding::inflate) {
exampleView.setBackgroundColor(Color.GRAY)
}
}
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
}
)