以编程方式将视图添加到ConstraintLayout

时间:2018-08-21 22:14:34

标签: android android-layout

我知道这个问题已经被问过多次了,但这似乎很难通过代码来实现。

我想要实现的是扩展ConstraintLayout并为其添加两个视图。我有以下代码:

class TestLayout @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private val ids = mutableListOf<Int>()

    init {
        addTextView()
        addTextView()

        val set = ConstraintSet()
        set.clone(this)

        set.connect(ids[0], ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 200)
        set.connect(ids[1], ConstraintSet.TOP, ids[0], ConstraintSet.BOTTOM)

        set.applyTo(this)
    }

    private fun addTextView() {
        val view = TextView(context)

        addView(view, LayoutParams(LayoutParams.MATCH_CONSTRAINT, LayoutParams.WRAP_CONTENT))

        view.id = View.generateViewId()
        view.text = view.id.toString()

        ids.add(view.id)
    }
}

运行此代码时,第一个视图正确显示,但是第二个视图在左上角(好像没有任何约束)。

我在这里到底想念什么?

1 个答案:

答案 0 :(得分:0)

您需要至少添加一个水平一个垂直约束,才能在 ConstraintLayout 中查看添加,

在这里,它在init构造函数中不满足:

set.connect(ids[0], ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 200) // no vertical constraint (Top/Bottom), so view will add at 0 position of y axis
set.connect(ids[1], ConstraintSet.TOP, ids[0], ConstraintSet.BOTTOM) // No horizontal constraint so that view 2 will jump to position (0,0)

这样做:

// Add constraints for View 1
set.connect(ids[0], ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 200)
set.connect(ids[0], ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 20) // Add top constraint to your view 1
set.connect(ids[0], ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, 200) // Optional if you want symmetry of view 1 in layout

// Add constraints for view 2
set.connect(ids[1], ConstraintSet.TOP, ids[0], ConstraintSet.BOTTOM)
set.connect(ids[1], ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 200) // Add start constraint to view 2
set.connect(ids[1], ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, 200) // Optional if you want symmetry of view 2 in layout

ConstraintLayoutConstraintSet阅读。