-4

I have four buttons in a LinearLayout. I want to set the width of these Button as 25%. How to do that?

VIISHRUT MAVANII
  • 11,410
  • 7
  • 34
  • 49
ZBorkala
  • 366
  • 3
  • 13
  • 3
    Possible duplicate of [What does android:layout\_weight mean?](https://stackoverflow.com/questions/3995825/what-does-androidlayout-weight-mean) – Martin Zeitler Apr 11 '19 at 02:17

3 Answers3

1

You don't need to write code for this. Just set the LinearLayout.weight_sum=4, set each Button.layout_weight=1 and width=0dp

Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51
AIMIN PAN
  • 1,563
  • 1
  • 9
  • 13
1

Here is a Solution

Set android:weightSum to parent layout/view and and set android:layout_weight to child layout/view. Note : Child layouts/views must be set with width android:layout_width 0.

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="4"  
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

    </LinearLayout>
scarecrow
  • 6,624
  • 5
  • 20
  • 39
VIISHRUT MAVANII
  • 11,410
  • 7
  • 34
  • 49
1

To change the width at runtime use the below code:

button_1=findViewById(R.id.button_1);
button_1.setLayoutParams(new LinearLayout.LayoutParams(100,100));

Now, if you want to set the width of 4 buttons to 25%, you can pass the weight attribute into LayoutParams.

The syntax for runtime equal weight is:

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT, weight in float);
yourView.setLayoutParams(param);

You can use below code to change width of buttons at runtime:

Button button1=findViewById(R.id.button1);
Button button2=findViewById(R.id.button2);
Button button3=findViewById(R.id.button3);
Button button4=findViewById(R.id.button4);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT,1.0f);
button1.setLayoutParams(param);
button2.setLayoutParams(param);
button3.setLayoutParams(param);
button4.setLayoutParams(param);

I hope it works for you.

The Amateur Coder
  • 789
  • 3
  • 11
  • 33
Android Geek
  • 8,956
  • 2
  • 21
  • 35