Jetpack Compose 和 Fragment混合嵌入页面
Fragment中使用Compose
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setContent {
Column(
modifier = Modifier
.fillMaxWidth()
.background(Color.Red)
.padding(8.dp)
) {
Text(
"这里是被嵌入的测试Fragment页面",
color = Color.White, fontSize = 21.sp,
modifier = Modifier.padding(16.dp)
)
}
}
}
}
Compose中使用Fragment
val context = LocalContext.current
if (context is FragmentActivity) {
AndroidView(factory = {
FragmentContainerView(it).apply {
id = View.generateViewId()
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
)
}
}, update = { view ->
context.supportFragmentManager.beginTransaction().replace(view.id, HDevFragment())
.commitNowAllowingStateLoss()
})
}
总结
主要通过ComposeView和AndroidView的使用实现。在传统View布局中,ComposeView相当于把Compose转换为View布局,通过ComposeView中的setContent进行界面布局书写;在Compose中,AndroidView提供了显示传统View的功能,只需要实现factory、update内容即可,上述代码通过FragmentContainerView容器进行构建,在update中进行实际fragment的嵌入。
1397

被折叠的 条评论
为什么被折叠?



