我试图使用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布局任务。


当前回答

 MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();
 layoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);

其他回答

这里有一句话:

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

核心-KTX:

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

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

试试这个

 LayoutParams params = new LayoutParams(
            LayoutParams.WRAP_CONTENT,      
            LayoutParams.WRAP_CONTENT
    );
    params.setMargins(left, top, right, bottom);
    yourbutton.setLayoutParams(params);
 MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();
 layoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);

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

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”检查,以防您试图对不支持页边距的东西运行此检查。