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

时间:2011-11-14 20:33:45

标签: android android-layout

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

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

5 个答案:

答案 0 :(得分:17)

使用以下代码设置属性:

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

答案 1 :(得分: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);

答案 2 :(得分:3)

使用LayoutParams获取高度,宽度和重力

LinearLayout.LayoutParams (int width, int height)

您可以使用WRAP_CONTENT作为整数。

然后最后两位有Button.setGravity()Button.setTextSize()

希望这有帮助。

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

button.setTextSize(32);
相关问题