Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a button's parameters programmatically

I'm trying to add a bunch of buttons to a layout like this:

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

My problem is how do I do this programmatically to all the buttons:

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

I've been looking at LayoutParams but it doesn't look complete. Like how do I set the textSize to 32 dip?

like image 202
Espen Avatar asked Nov 14 '11 20:11

Espen


1 Answers

Set your attributes using the following code:

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

If you want to specify the text size units use:

button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 32);
like image 123
dymmeh Avatar answered Nov 03 '22 14:11

dymmeh