首页 > 解决方案 > 具有预定义视图的自定义视图组无法正常工作

问题描述

我正在使用以下代码:

class TestConstraintLayout(context: Context): ConstraintLayout(context) {
    private val simpleConstraintSet = SimpleConstraintSet(this)

    private val textView = AppCompatTextView(context)

    init {
        textView.id = View.generateViewId()
        textView.layoutParams = ConstraintLayout.LayoutParams(
            10,
            ConstraintLayout.LayoutParams.MATCH_PARENT
        )

        textView.setBackgroundColor(-10000)

        simpleConstraintSet.build {
            textView leftToLeftOf parent
            textView topToTopOf parent
            textView rightToRightOf parent
            textView bottomToBottomOf parent

            textView withHorizontalBiasOf 0.3f
        }

        addView(textView)
    }

}

尽管存在水平偏差,但我得到以下结果:

在此处输入图像描述

一切都在我的自定义布局之外完美运行,所以我想这不是设置 layoutparams 还是其中的约束的方法。

标签: androidkotlinparametersconstraints

解决方案


我发现了我的错误,我应该在约束和参数之前添加带有 addView 的 textView。


推荐阅读