我试图使用Java(不是XML)创建一个线性布局的按钮,填充屏幕,并有边缘。下面是没有边距的代码:

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

所以这很好,但你到底如何给按钮空白,使它们之间有空间?我尝试使用线性布局。MarginLayoutParams,但它没有weight成员,所以不好。如果你在构造函数中传入lp,它也不会起作用。

这不可能吗?因为它看起来很像,它也不是第一个只能用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);

其他回答

试试这个

 LayoutParams params = new LayoutParams(
            LayoutParams.WRAP_CONTENT,      
            LayoutParams.WRAP_CONTENT
    );
    params.setMargins(left, top, right, bottom);
    yourbutton.setLayoutParams(params);

核心-KTX:

 updateLayoutParams<RecyclerView.LayoutParams> {
                topMargin = 10
                rightMargin = 10
                bottomMargin = 10
                leftMargin = resources.getDimensionPixelSize(R.dimen.left)
            }

而不是RecycleView,使用任何视图在ViewGroup。

要直接向项目添加页边距(某些项目允许直接编辑页边距),您可以执行以下操作:

LayoutParams lp = ((ViewGroup) something).getLayoutParams();
if( lp instanceof MarginLayoutParams )
{
    ((MarginLayoutParams) lp).topMargin = ...;
    ((MarginLayoutParams) lp).leftMargin = ...;
    //... etc
}
else
    Log.e("MyApp", "Attempted to set the margins on a class that doesn't support margins: "+something.getClass().getName() );

...这种工作不需要了解/编辑周围的布局。请注意“instanceof”检查,以防您试图对不支持页边距的东西运行此检查。

我已经直接使用下面的代码设置了边缘

LinearLayout layout = (LinearLayout)findViewById(R.id.yourrelative_layout);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);            
params.setMargins(3, 300, 3, 3); 
layout.setLayoutParams(params);

这里唯一需要注意的是,LayoutParams应该被导入到android.widget.RelativeLayout包中。LayoutParams,否则将会出现错误。

这里有一句话:

((LinearLayout.LayoutParams) yourLinearLayout.getLayoutParams()).marginToAdd = ((int)(Resources.getSystem().getDisplayMetrics().density * yourDPValue));