Android 如何设置按钮';以编程方式调用参数

Android 如何设置按钮';以编程方式调用参数,android,android-layout,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 ); } for(int i=0;i

我试图在布局中添加一组按钮,如下所示:

for( int i = 0; i < 10; i++ ) {
    Button button = new Button( this );
    button.setText( "" + i );
    ( ( LinearLayout )dialog.findViewById( R.id.Buttons ) ).addView( button );
}
for(int i=0;i<10;i++){
按钮按钮=新按钮(此按钮);
按钮.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?

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

LinearLayout.LayoutParams (int width, int height)
在这里,您可以对ints使用
WRAP\u内容

最后两个是
Button.setGravity()
Button.setTextSize()


希望这有帮助。

您可以使用
LayoutParams
对象进行布局设置,并通过
按钮
类设置文本大小


也可以使用设置重力。

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

button.setTextSize(32);

LayoutParams
与包含视图的父视图组相关。因此,在您的情况下,它是一个
线性布局
,因此您需要为该布局创建参数。下面是我要说的:

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

使用以下代码设置属性:

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

如何使用Button.setTextSize()指定dip?public void setTextSize(整数单位,浮点大小);这里的单位是“复杂度”\u单位度”\u倾角,大小=文本大小。但我在重力方面遇到了问题。setGravity(Gravity.CENTER\u HORIZONTAL)与xml文件中的android:layout\u Gravity=“CENTER\u HORIZONTAL”的功能不同。xml文件按钮居中,但不是使用setGravity()创建的按钮。请使用布局参数尝试此操作:LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,Gravity.CENTER_HORIZONTAL);或者在初始化参数调用后:params.gravity=gravity.CENTER\u HORIZONTAL;setGravity不能按您想要的方式工作的原因是因为android:gravity不同于android:layout\u GravityTanx,但我已经找到了答案。我没有在每个按钮上设置布局重力,而是在父视图LinearLayout上设置重力。