android - 以编程方式将片段添加到约束布局
问题描述
我正在尝试将两个片段添加到约束布局,然后设置它们的约束,以确保下部片段始终捕捉到应用程序布局的底部,并且上部片段可以填充任何剩余空间。我执行此操作的代码如下所示:
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.add(R.id.app_con_layout,fragmentA)
fragmentTransaction.add(R.id.app_con_layout,fragmentB)
fragmentTransaction.commit()
val mConstraintLayout = findViewById<ConstraintLayout>(R.id.app_con_layout)
val set = ConstraintSet()
set.clone(mConstraintLayout)
set.connect(fragmentA.id, ConstraintSet.TOP, R.id.app_toolbar, ConstraintSet.BOTTOM)
set.connect(fragmentB.id, ConstraintSet.BOTTOM, mConstraintLayout.id, ConstraintSet.BOTTOM)
set.applyTo(mConstraintLayout)
这不起作用,两个片段似乎最终彼此重叠。我的理解是片段不会获得唯一的 ID,而是我应该使用标签作为片段事务的一部分,以便以后能够唯一地引用片段。但这似乎与 ConstraintSet 的connect
方法不兼容,后者需要一个整数 id。
解决这个问题的正确方法是什么?我可以将框架布局添加到 xml 中的约束布局,然后将片段添加到其中,但这感觉像是一种解决方法,所以我怀疑我遗漏了一些东西。
解决方案
您为 使用了错误的 ID set.connect(…)
。Fragment 有 View,如果你想将它传递给connect(…)
. 这对我来说太复杂了,因为你需要等到 Fragment 生命周期开始(fragmentTransaction.commit()
是异步的)。不知道commitNow()
能不能帮到你。
我可以将框架布局添加到 xml 中的约束布局
如果我是你,我会采取这种方法。这样,布局将保留在 XML 中,并且仅将片段添加到它们的占位符(并处理它们的生命周期和事件传播)将以编程方式完成。