繁体   English   中英

如何在android studio中以编程方式更改按钮的宽度

[英]How to change programmatically button's width in android studio

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

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

这是一个解决方案

android:weightSum设置为父布局/视图,并将android:layout_weight设置为子布局/视图。 注意:子布局/视图的宽度必须设置为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>

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

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

现在,如果要将 4 个按钮的宽度设置为 25%,可以将 weight 属性传递给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);

我希望这个对你有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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