Android - ConstraintLayout 以编程方式设置百分比高度?

beg*_*ner 9 layout android android-studio android-constraintlayout

这是我的布局:

...
<android.support.constraint.ConstraintLayout   
android:layout_width="0dp"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent="0.6"
>
            <android.support.constraint.ConstraintLayout
                android:id="@+id/myclayout"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                app:layout_constraintHeight_percent="0.2"
                app:layout_constraintTop_toTopOf="parent"
                ></android.support.constraint.ConstraintLayout>


 </android.support.constraint.ConstraintLayout>
...
Run Code Online (Sandbox Code Playgroud)

如何以编程方式设置constraintHeight_percent?

我尝试使用 ConstraintSet 但没有用

ConstraintSet set = new ConstraintSet();
set.constrainPercentHeight(R.id.myclayout, (float) 0.4);
set.applyTo(((ConstraintLayout) vw.findViewById(R.id.myclayout)));
Run Code Online (Sandbox Code Playgroud)

beg*_*ner 15

正确答案是:

    ConstraintLayout mConstrainLayout  = (ConstraintLayout) vw.findViewById(R.id.myclayout);
    ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) mConstrainLayout.getLayoutParams();
    lp.matchConstraintPercentHeight = (float) 0.4;
    mConstrainLayout.setLayoutParams(lp);
Run Code Online (Sandbox Code Playgroud)


Tom*_*ard 5

我使用ConstraintSet来更新ConstraintLayout子级的宽度和高度:

        val set = ConstraintSet()
        set.clone(parentLayout) // parentLayout is a ConstraintLayout
        set.constrainPercentWidth(childElement.id, .5f)
        set.constrainPercentHeight(childElement.id, .5f)
        set.applyTo(parentLayout)
Run Code Online (Sandbox Code Playgroud)

...浮点值应该是映射到单位间隔的百分比。