How to set button options programmatically

I am trying to add a few 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 can I do this programmatically for all buttons:

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

I am looking at LayoutParams, but it does not look complete. For example, how do I set textSize to 32 dip?

+7
source share
5 answers

Set your attributes with 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 text size units, use:

 button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 32); 
+16
source

LayoutParams refers to the parent ViewGroup that will contain the view. Therefore, in your case, this is LinearLayout , so you need to create parameters for this. This is what I am talking about:

 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); 
+4
source

Use LayoutParams for height, width and gravity with

 LinearLayout.LayoutParams (int width, int height) 

where you can use WRAP_CONTENT for ints.

Then for the last two there is Button.setGravity() and Button.setTextSize() .

Hope this helps.

+3
source

You would use the LayoutParams object for layout options and use the setTextSize () from the Button class to set the text size.

You can set gravity with setGravity () .

0
source

TextSize is not part of the layout options. To set textSize you must

 button.setTextSize(32); 
0
source

All Articles