gpt4 book ai didi

android - Jetpack Compose 中的 fragment 容器

转载 作者:行者123 更新时间:2023-12-02 13:44:12 28 4
gpt4 key购买 nike

我想使用 开发单个 Activity 多 fragment 应用程序喷气背包撰写 .
对于 recyclerView,我们有 Vertical 和 Horizo​​ntalScroller。但是,对于 fragment 我应该使用什么。

fun loadFragment(fragment: Fragment) {
val transaction:FragmentTransaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.f_container, fragment)
transaction.addToBackStack(null)
transaction.commit()
}

在这种情况下,我没有 R.id.f_container 因为我只使用 compose 创建 UI。
<FrameLayout
android:id="@+id/f_container"
android:layout_width="match_parent"
android:layout_height="match_parent"`enter code here`
app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:layout_constraintEnd_toEndOf="parent"
tools:layout_editor_absoluteY="-56dp">
</FrameLayout>

最佳答案

您可以创建自己的 @Composable FragmentContainer 函数

@Composable
fun FragmentContainer(
modifier: Modifier = Modifier,
fragmentManager: FragmentManager,
commit: FragmentTransaction.(containerId: Int) -> Unit
) {
val containerId by rememberSaveable { mutableStateOf(View.generateViewId()) }
var initialized by rememberSaveable { mutableStateOf(false) }
AndroidView(
modifier = modifier,
factory = { context ->
FragmentContainerView(context)
.apply { id = containerId }
},
update = { view ->
if (!initialized) {
fragmentManager.commit { commit(view.id) }
initialized = true
} else {
fragmentManager.onContainerAvailable(view)
}
}
)
}

/** Access to package-private method in FragmentManager through reflection */
private fun FragmentManager.onContainerAvailable(view: FragmentContainerView) {
val method = FragmentManager::class.java.getDeclaredMethod(
"onContainerAvailable",
FragmentContainerView::class.java
)
method.isAccessible = true
method.invoke(this, view)
}
然后在 Activity 中使用它
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FragmentContainer(
modifier = Modifier.fillMaxSize(),
fragmentManager = supportFragmentManager,
commit = { add(it, YourFragment()) }
)
}
}
或在 fragment 中
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = ComposeView(requireContext()).apply {
setContent {
FragmentContainer(
modifier = Modifier.fillMaxSize(),
fragmentManager = parentFragmentManager,
commit = { add(it, YourNestedFragment()) }
)
}
}

关于android - Jetpack Compose 中的 fragment 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60520145/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com