Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - ConstraintLayout set Percent Height programmatically?

here is my layout :

...
<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>
...

how to set constraintHeight_percent programmatically ?

I tried with ConstraintSet but did not work

ConstraintSet set = new ConstraintSet();
set.constrainPercentHeight(R.id.myclayout, (float) 0.4);
set.applyTo(((ConstraintLayout) vw.findViewById(R.id.myclayout)));
like image 496
beginner Avatar asked Jan 25 '19 09:01

beginner


People also ask

How do I set guidelines in ConstraintLayout?

There are two types of guidelines: Now we can position guidelines in three different ways: By using (layout_constraintGuide_begin) to specify a fixed distance from the left or the top of a layout. By using (layout_constraintGuide_end) to specify a fixed distance from the right or the bottom of a layout.

How to Constraint layout in Android?

Open your layout in Android Studio and click the Design tab at the bottom of the editor window. In the Component Tree window, right-click the layout and click Convert layout to ConstraintLayout.

What is ConstraintSet?

Used to create a horizontal create guidelines. This view is invisible, but it still takes up space for layout purposes.

What is constrainedWidth?

constrainedWidth. Specify if the horizontal dimension is constrained in case both left & right constraints are set and the widget dimension is not a fixed dimension.


2 Answers

the right answer is :

    ConstraintLayout mConstrainLayout  = (ConstraintLayout) vw.findViewById(R.id.myclayout);
    ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) mConstrainLayout.getLayoutParams();
    lp.matchConstraintPercentHeight = (float) 0.4;
    mConstrainLayout.setLayoutParams(lp);
like image 144
beginner Avatar answered Oct 17 '22 07:10

beginner


I went with using a ConstraintSet to update the width and height of a ConstraintLayout's child:

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

...the float values should be a percentage mapped to the unit interval.

like image 25
Tom Howard Avatar answered Oct 17 '22 05:10

Tom Howard