如何以编程方式设置按钮的参数

问题描述 投票:0回答:6

我正在尝试向这样的布局添加一堆按钮:

for( int i = 0; i < 10; i++ ) {
    Button button = new Button( this );
    button.setText( "" + i );
    ( ( LinearLayout )dialog.findViewById( R.id.Buttons ) ).addView( button );
}

我的问题是如何以编程方式对所有按钮执行此操作:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:textSize="32dip" />

我一直在查看 LayoutParams 但它看起来并不完整。比如如何将 textSize 设置为 32 dial?

android android-layout
6个回答
20
投票

使用以下代码设置您的属性:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setGravity(Gravity.CENTER_HORIZONTAL);
button.setTextSize(32);

如果您想指定文本大小单位,请使用:

button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 32);

4
投票

LayoutParams
与包含视图的父级
ViewGroup
相关。因此,在您的情况下,它是一个
LinearLayout
,因此您需要为该创建参数。这就是我要说的:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.weight = 1f;

Button button = new Button(this);
button.setLayoutParams(lp);
button.setText("" + i);
((LinearLayout)dialog.findViewById(R.id.Buttons)).addView(button);

3
投票

使用 LayoutParams 来设置高度、宽度和重力

LinearLayout.LayoutParams (int width, int height)

您可以在其中使用

WRAP_CONTENT
表示整数。

最后两个是

Button.setGravity()
Button.setTextSize()

希望这有帮助。


0
投票

您可以使用

LayoutParams
对象进行布局设置,并使用 Button 类中的
setTextSize()
设置文本大小。

您也可以使用 setGravity() 设置重力。


0
投票

TextSize 不在布局参数内。要设置 textSize 你必须

button.setTextSize(32);

0
投票

对于那些想要修改现有参数的人,您可以从 Button 获取 LayoutParams 并将其类型转换为按钮所在的布局类型:

//get the current params and typecast to whichever layout the button is in
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) button.getLayoutParams();
//change something in the params
params.setMargins(0, 0, 0, 200);
//set the button with the new params
button.setLayoutParams(params);
© www.soinside.com 2019 - 2024. All rights reserved.