Search code examples
androidandroid-linearlayoutandroid-screen-supportandroid-layout-weight

Horizontal buttons with max width and weight


I want to have two horizontal buttons with the first one taking 60 % of the layout width and the second one taking 40%. Both buttons have a max width for very large screens and in that case it has to be left aligned.

I tried with LinearLayout as shown below. But I am not sure if max width would work with weight. What is the correct way of implementing this?

 <LinearLayout
     android:layout_width="0dp"
     android:layout_height="wrap_content"
     android:layout_marginTop="40dp"
     android:orientation="horizontal"
     android:weightSum="1"
     app:layout_constraintBottom_toBottomOf="parent"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     app:layout_constraintTop_toBottomOf="@id/eventTitle">

     <Button
         android:id="@+id/one"
         android:layout_width="0dp"
         android:layout_height="80dp"
         android:layout_weight=".6"
         android:maxWidth="547dp"
         android:text="One" />

     <Button
         android:id="@+id/two"
         android:layout_width="0dp"
         android:layout_height="80dp"
         android:layout_marginLeft="32dp"
         android:layout_weight=".4"
         android:maxWidth="349dp"
         android:text="Two" />


Solution

  • The attribute maxWidth should be set in your LinearLayout:

    <LinearLayout
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:layout_marginTop="40dp"
         android:orientation="horizontal"
         android:weightSum="1"
         android:maxWidth="896dp"
         app:layout_constraintBottom_toBottomOf="parent"
         app:layout_constraintLeft_toLeftOf="parent"
         app:layout_constraintRight_toRightOf="parent"
         app:layout_constraintTop_toBottomOf="@id/eventTitle">
    

    Remove it from your child views and the corresponding weight will be used.