我需要在一个LinearLayout上添加多个按钮,但是我想让这些按钮之间相距5px。我找不到设置Button边距的方式。有什么想法吗?
使用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字段。
试试这个:
//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);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btnContainer.getLayoutParams();
params.setMargins(5, 50, 10, 0); //left, top, right, bottom
view_whwre_set_margin.setLayoutParams(params);
lParam.setMargins(20, 20, 20, 20);
它会给LinearLayout添加边距,而不是按钮。例如,如果有两个并排的按钮,它不会在按钮之间添加空间!这正是我的目标!谢谢! - Droid-Bird