我必须在LinearLayout上添加多个按钮。但我想把这些按钮分开5px。我找不到设置按钮边距的方法。有什么想法吗?
答案 0 :(得分:19)
使用button元素的layout_margin属性。这不起作用吗?
<Button android:layout_margin="5px" (...)/>
在java中创建按钮时,LayoutParams用于指定边距等。
Button button = new Button();
(....)
params = new LinearLayout.LayoutParams();
params.leftMargin = 5;
(set params as you need)
parent.addView(button, params);
您使用的LayoutParams必须与您添加按钮的布局相匹配(请参阅http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html)。对于LinearLayout,请使用LinearLayout.LayoutParams并相应地设置* Margin字段。
答案 1 :(得分:8)
试试这个:
//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);
答案 2 :(得分:3)
MarginLayoutParams params = (MarginLayoutParams) vector8.getLayoutParams();
params.width = 200; params.leftMargin = 100; params.topMargin = 200;
vector8.setLayoutParams(params);
需要使用类型:MarginLayoutParams
答案 3 :(得分:0)
为按钮添加填充也可以解决您的问题。看一下这个 http://developer.android.com/resources/tutorials/views/hello-formstuff.html#CustomButton
答案 4 :(得分:0)
使用此代码在运行时设置边距
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btnContainer.getLayoutParams();
params.setMargins(5, 50, 10, 0); //left, top, right, bottom
view_whwre_set_margin.setLayoutParams(params);