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

Esp*_*pen 7 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 );
}
Run Code Online (Sandbox Code Playgroud)

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

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:textSize="32dip" />
Run Code Online (Sandbox Code Playgroud)

我一直在看LayoutParams,但它看起来并不完整.就像我如何将textSize设置为32 dip?

dym*_*meh 18

使用以下代码设置属性:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setGravity(Gravity.CENTER_HORIZONTAL);
button.setTextSize(32);
Run Code Online (Sandbox Code Playgroud)

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

button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 32);
Run Code Online (Sandbox Code Playgroud)