我正在尝试使用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在其构造函数中传递它,它也不起作用。
LinearLayout.MarginLayoutParams
这不可能吗?因为它看起来确实可靠,而且它不是你只能使用XML进行的第一个Android布局任务。
这是一些实现它的代码:
LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(30, 20, 30, 0); Button okButton=new Button(this); okButton.setText("some text"); ll.addView(okButton, layoutParams);