开发者

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 a开发者_开发百科part. I could not find a way to set a margin of a Button. Any idea?


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.


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


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

Need use type of: MarginLayoutParams


Adding padding to the buttons would also solve your problem. Check this out http://developer.android.com/resources/tutorials/views/hello-formstuff.html#CustomButton


use this code to set margin at runtime

  LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btnContainer.getLayoutParams();
        params.setMargins(5, 50, 10, 0); //left, top, right, bottom
        view_whwre_set_margin.setLayoutParams(params);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜