Search code examples
androidandroid-constraintlayout

ConstraintLayout take height of another view android


I am using constraintLayout

I wanted one of my view to take height of another view

I wanted my right Textview to take the height of left TextView

My code :

<TextView
            android:id="@+id/tv_cal_consumed"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/button_selector_curved"
            android:drawableLeft="@drawable/ic_add"
            android:drawablePadding="5dp"
            android:gravity="start"
            android:padding="10dp"
            android:text="@string/cal_consumed"
            android:textColor="@color/white"
            android:textSize="@dimen/text_small"
            android:textStyle="normal"
            android:typeface="normal"
            app:layout_constraintHorizontal_chainStyle="spread_inside"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@+id/tv_cal_burnt"
            app:layout_constraintTop_toBottomOf="@+id/con_info" />


        <TextView
            android:id="@+id/tv_cal_burnt"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"

            android:background="@drawable/button_selector_curved"
            android:drawableLeft="@drawable/ic_add"
            android:drawablePadding="5dp"
            android:gravity="start"
            android:padding="10dp"
            android:text="@string/cal_burnt"
            android:textColor="@color/white"
            android:textSize="@dimen/text_small"
            android:textStyle="normal"
            android:typeface="normal"
            app:layout_constraintTop_toTopOf="@+id/tv_cal_consumed"
            app:layout_constraintLeft_toRightOf="@+id/tv_cal_consumed"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toBottomOf="@+id/tv_cal_consumed" />

Current output:

enter image description here


Solution

  • Change the layout_height to 0dp (match constraints) for tv_cal_burnt. That will cause the TextView to grow to the same height as the other view. Your top and bottom constraints are already set correctly to make this work. See this.

    Using 0dp, which is the equivalent of "MATCH_CONSTRAINT"

       <TextView
            android:id="@+id/tv_cal_burnt"
            android:layout_height="0dp"
       ...
    


    Update: If you don't know in advance which view will be taller/wider due to localization, etc., I suggest taking a look at this answer to a similar question. The concept outlined in that answer works for heights and widths - just interchange app:layout_constraintWidth_min="wrap" for app:layout_constraintHeight_min="wrap". (As of ConstraintLayout 2.0.4)