Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align a layout to left while both left and right constraints are applied to it inside Constraint Layout?

This is the layout I want to design:

enter image description here

As you can see from the image, I want the linear layout to be constrained to both Item A and Item B and I want it aligned to left. I couldn't find any way to implement this inside a Constraint Layout. When I use this:

<LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/ui_size_xs">

linear layout moves to the middle. When I use this:

<LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="0dp"
        android:layout_height="@dimen/ui_size_xs">

the linear layout occupies the whole area between Items A and B. I want the linear layout to be wrap-content but should also align to the left like in the image. The only solution I could find is to create a new layout as parent of this linear layout and give 0dp to new parent linear layout and wrap-conent to this layout child layout. I don't want to do that. Is there any way to achieve this without creating any extra layout?

like image 395
Jayesh Babu Avatar asked Oct 13 '25 00:10

Jayesh Babu


1 Answers

As mentioned in offical docs,

The default when encountering such opposite constraints is to center the widget; but you can tweak the positioning to favor one side over another using the bias attributes:

  • layout_constraintHorizontal_bias
  • layout_constraintVertical_bias

Try the following and see if it works

<LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/ui_size_xs"
        app:layout_constraintHorizontal_bias="0.3"
        app:layout_constraintLeft_toRightOf="item1id"
        app:layout_constraintRight_toLeft="item2id">

// try different horizontal bias values to meet your need
like image 165
Dhanuesh Avatar answered Oct 14 '25 13:10

Dhanuesh