简体   繁体   中英

How to change programmatically button's width in android studio

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

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

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>

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM