Android:如何以编程方式设置LinearLayout边距

问题描述 投票:0回答:1

我一直在尝试为以编程方式创建的LinearLayout设置边距

LinearLayout linearLayout = new LinearLayout(this);
setMargins(linearLayout,20,20,20,20);

   private void setMargins (View view, int left, int top, int right, int bottom) {
    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();

        final float scale = getBaseContext().getResources().getDisplayMetrics().density;
        // convert the DP into pixel
        int l =  (int)(left * scale + 0.5f);
        int r =  (int)(right * scale + 0.5f);
        int t =  (int)(top * scale + 0.5f);
        int b =  (int)(bottom * scale + 0.5f);

        p.setMargins(l, t, r, b);
        view.requestLayout();
    }
}

但它没有用,所以我从另一个答案中尝试了这个

parameter =  (LinearLayout.LayoutParams) linearLayout.getLayoutParams();
parameter.setMargins(leftMargin, parameter.topMargin, parameter.rightMargin, parameter.bottomMargin); // left, top, right, bottom
linearLayout.setLayoutParams(parameter);

但我得到“无法解析符号参数”

如何将边距设置为以编程方式创建的视图?

android margins programmatically-created
1个回答
0
投票

试试这个:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

layoutParams.setMargins(10, 10, 10, 10);
linearLayout.setLayoutParams(layoutParams);
© www.soinside.com 2019 - 2024. All rights reserved.