[英]How to change programmatically button's width in android studio
I have four buttons in a LinearLayout
.我在
LinearLayout
有四个按钮。 I want to set the width of these Button
as 25%.我想将这些
Button
的宽度设置为 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
只需设置
LinearLayout.weight_sum=4
,设置每个Button.layout_weight=1
和width=0dp
Here is a Solution这是一个解决方案
Set android:weightSum
to parent layout/view and and set android:layout_weight
to child layout/view.将
android:weightSum
设置为父布局/视图,并将android:layout_weight
设置为子布局/视图。 Note : Child layouts/views must be set with width android:layout_width
0.注意:子布局/视图的宽度必须设置为
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
.现在,如果要将 4 个按钮的宽度设置为 25%,可以将 weight 属性传递给
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.我希望这个对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.