【发布时间】:2011-01-29 16:50:28
【问题描述】:
我正在尝试使用 Java(不是 XML)创建一个带有按钮的 LinearLayout,这些按钮可以填满屏幕并有边距。这是没有边距的代码:
LinearLayout buttonsView = new LinearLayout(this);
buttonsView.setOrientation(LinearLayout.VERTICAL);
for (int r = 0; r < 6; ++r) {
Button btn = new Button(this);
btn.setText("A");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); // Verbose!
lp.weight = 1.0f; // This is critical. Doesn't work without it.
buttonsView.addView(btn, lp);
}
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
setContentView(buttonsView, lp);
这样可以正常工作,但是到底如何给按钮留出边距以便它们之间有空间?我尝试使用LinearLayout.MarginLayoutParams,但它没有weight 成员,所以它不好。如果你在它的构造函数中传递lp,它也不起作用。
这不可能吗?因为它看起来确实如此,而且它不会是您只能在 XML 中执行的第一个 Android 布局任务。
【问题讨论】:
-
developer.android.com/reference/android/view/…, int, int, int) 而不是 layoutParams.setMargins(30, 20, 30, 0);你把 layoutParams.setMargins(30dp, 20dp, 30dp, 0dp);
-
setMargins 将 int 作为参数。您只能使用 xml 属性提供“dp”
标签: java android layout view margin