在 kotlin 中以编程方式将视图高度设置为 matchparent

set view height as matchparent programmatically in kotlin

我需要在我的 constraintLayout class.

中以编程方式将按钮的高度设置为 matchparent
open class Myword @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
     ) : ConstraintLayout(context,attrs) {

    var set = ConstraintSet()
    val tastoetim= Button(this.context)
    init{
        this.addView(tastoetim)
        tastoetim.requestLayout()


        set.connect(tastoetim.id, ConstraintSet.LEFT,this.id, ConstraintSet.LEFT, 10)
        set.connect(tastoetim.id, ConstraintSet.BOTTOM,this.id, ConstraintSet.BOTTOM, 0)

        tastoetim.minHeight = 0
        tastoetim.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT

    } }

这行不通。

正如此 post (set height of imageview as matchparent programmatically) 的作者已经指出的,none 这些答案有效。

首先设置解决:

tastoetim.setMinHeight(0);
tastoetim.setMinimumHeight(0);

然后:

tastoetim.getLayoutParams().height= ViewGroup.LayoutParams.MATCH_PARENT;

setMinHeight是ButtonView定义的,setMinimumHeight是View定义的。根据文档,使用两个值中的较大者,因此必须同时设置。

来自 documentation for ConstraintLayout:

Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".

根据我的经验,使用 MATCH_PARENT 可能会产生一些奇怪的结果。

在您的情况下,您需要执行以下操作:

open class Myword @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {


    init {
        val tastoetim = Button(this.context)
        // The new Button needs an id, otherwise, it is "NO_ID" (-1)
        tastoetim.id = View.generateViewId()
        val lp = ConstraintLayout.LayoutParams(
            ConstraintLayout.LayoutParams.WRAP_CONTENT,
            ConstraintLayout.LayoutParams.MATCH_CONSTRAINT
        )
        this.addView(tastoetim, lp)

        // Get the ConstraintSet only after the view is added.
        val set = ConstraintSet()
        set.clone(this)

        set.connect(
            tastoetim.id,
            ConstraintSet.LEFT,
            ConstraintSet.PARENT_ID,
            ConstraintSet.LEFT,
            10
        )

        // For match constraints, we need a top and a bottom view to connect to. Here the
        // parent top is assumed, but it could be another view.
        set.connect(
            tastoetim.id,
            ConstraintSet.TOP,
            ConstraintSet.PARENT_ID,
            ConstraintSet.TOP,
            0
        )
        set.connect(
            tastoetim.id,
            ConstraintSet.BOTTOM,
            ConstraintSet.PARENT_ID,
            ConstraintSet.BOTTOM,
            0
        )

        // Apply the updated ConstraintSet back to the ConstraintLayout.
        set.applyTo(this)
    }
}

另一种方法是将高度设置为等于父级的高度。

假设父级是一个线性布局,id = layVert:

tastoetim.layoutParams.height = findViewById<LinearLayout>(R.id.layVert).layoutParams.height