Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add margin to a Button at run time?

I have to add more than one buttons on a LinearLayout. But I want to put those buttons say 5px apart. I could not find a way to set a margin of a Button. Any idea?

like image 848
Droid-Bird Avatar asked Aug 17 '11 14:08

Droid-Bird


3 Answers

Use the layout_margin property of the button element. Does that not work?

<Button android:layout_margin="5px" (...)/>

Edit

When creating a button in java, LayoutParams is used to specify margins and so.

Button button = new Button();
(....)
params = new LinearLayout.LayoutParams();
params.leftMargin = 5;
(set params as you need)
parent.addView(button, params);

The LayoutParams you use must match the Layout you add your button in (see http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html). For a LinearLayout, use a LinearLayout.LayoutParams and set the *Margin fields accordingly.

like image 185
njzk2 Avatar answered Oct 11 '22 23:10

njzk2


Try this:

//Assuming your button is in a LinearLayout as stated
LinearLayout.LayoutParams params = myButton.getLayoutParams();
params.setMargins(0, 0, 0, 0) //left, top, right, bottom
myButton.setLayoutParams(params);
like image 8
Kevin Coppock Avatar answered Oct 11 '22 21:10

Kevin Coppock


MarginLayoutParams params = (MarginLayoutParams) vector8.getLayoutParams();
params.width = 200; params.leftMargin = 100; params.topMargin = 200;
vector8.setLayoutParams(params);

Need use type of: MarginLayoutParams

like image 3
Lyusten Elder Avatar answered Oct 11 '22 23:10

Lyusten Elder