如何在安卓工作室中以编程方式更改按钮的宽度



我在一个LinearLayout中有四个按钮。我想将这些Button的宽度设置为 25%。怎么做?

你不需要为此编写代码。只需设置LinearLayout.weight_sum=4,设置每个Button.layout_weight=1width=0dp

这是一个解决方案

android:weightSum设置为父布局/视图,并将android:layout_weight设置为子布局/视图。注意:子布局/视图的宽度必须设置为 0 android:layout_width

<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>

若要在运行时更改宽度,请使用以下代码:

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

现在,如果要将4个按钮的宽度设置为25%,则可以将权重属性传递给LayoutParams

运行时相等权重的语法为:

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

您可以使用以下代码在运行时更改按钮的宽度:

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);

我希望它对你有用。

最新更新