将LinearLayout添加到ConstraintLayout时,TextViews消失
Posted
技术标签:
【中文标题】将LinearLayout添加到ConstraintLayout时,TextViews消失【英文标题】:When adding LinearLayout to ConstraintLayout, TextViews disappear 【发布时间】:2021-12-31 08:56:36 【问题描述】:我制作了一个 LinearLayout 模板 xml,其中有一个 ImageView 和 2 个 TextView,我正在尝试以编程方式将它添加到我的 ConstraintLayout。如果我将它添加到 LinearLayout:
val layout: LinearLayout = root.findViewById(R.id.linearLayoutBlockSequence)
val inflater = LayoutInflater.from(context)
val linearLayout = inflater.inflate(R.layout.linearlayout_block, null, false) as LinearLayout
linearLayout.id = View.generateViewId()
layout.addView(linearLayout)
效果很好:
但是当我将它添加到我的 ConstraintLayout 时:
val constraintLayout: ConstraintLayout = root.findViewById(R.id.constraintLayoutBlockSequence)
val inflater = LayoutInflater.from(context)
val linearLayout = inflater.inflate(R.layout.linearlayout_block, null, false) as LinearLayout
linearLayout.id = View.generateViewId()
constraintLayout.addView(linearLayout)
val constraintSet = ConstraintSet()
constraintSet.clone(constraintLayout)
constraintSet.connect(linearLayout.id, ConstraintSet.TOP, R.id.linearLayoutBlockSequence, ConstraintSet.BOTTOM, 0)
constraintSet.connect(linearLayout.id, ConstraintSet.END, R.id.constraintLayoutBlockSequence, ConstraintSet.END, 0)
constraintSet.connect(linearLayout.id, ConstraintSet.START, R.id.constraintLayoutBlockSequence, ConstraintSet.START, 0)
constraintSet.applyTo(constraintLayout)
TextView 不再存在:
我做错了什么?
【问题讨论】:
constraintSet.connect(linearLayout.id, ConstraintSet.END, R.id.constraintLayoutBlockSequence, ConstraintSet.END, 0)
只是问,但这不应该是R.id.linearLayoutBlockSequence
而不是constraintLayoutBlockSequence
吗?
【参考方案1】:
ConstraintLayout 和 LinearLayout 的宽度是否设置为包裹内容?也许问题是 ConstraintLayout 在创建时看不到 TextViews。在将所有元素添加到 ConstraintLayout 后尝试添加此代码:
constraintLayout.requestLayout()
这应该会强制重新绘制布局,现在包括其中的 TextView 的宽度。
【讨论】:
以上是关于将LinearLayout添加到ConstraintLayout时,TextViews消失的主要内容,如果未能解决你的问题,请参考以下文章
如何将 RecyclerView 添加到 LinearLayout(高度问题)
为啥我需要调用 removeView() 才能将视图添加到我的 LinearLayout
将 android:layoutAnimation 添加到 LinearLayout 会导致 FC