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


当前回答

/*
 * invalid margin
 */
private void invalidMarginBottom() {
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) frameLayoutContent.getLayoutParams();
    lp.setMargins(0, 0, 0, 0);
    frameLayoutContent.setLayoutParams(lp);
}

你应该注意视图的viewGroup的类型。在上面的代码中,例如,我想要改变frameLayout的边缘,而frameLayout的视图组是RelativeLayout,所以你需要隐藏到(RelativeLayout. layoutparams)

其他回答

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

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

/*
 * invalid margin
 */
private void invalidMarginBottom() {
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) frameLayoutContent.getLayoutParams();
    lp.setMargins(0, 0, 0, 0);
    frameLayoutContent.setLayoutParams(lp);
}

你应该注意视图的viewGroup的类型。在上面的代码中,例如,我想要改变frameLayout的边缘,而frameLayout的视图组是RelativeLayout,所以你需要隐藏到(RelativeLayout. layoutparams)

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

下面是一些小代码来完成它:

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

核心-KTX:

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

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