【问题标题】:Android: How to set LinearLayout marging programmaticallyAndroid:如何以编程方式设置 LinearLayout 边距
【发布时间】:2019-03-17 13:58:14
【问题描述】:

我一直在尝试为以编程方式创建的 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);

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

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

【问题讨论】:

  • 你初始化参数了吗? LinearLayout.LayoutParams 参数 =...

标签: android margins programmatically-created


【解决方案1】:

试试这个:

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

layoutParams.setMargins(10, 10, 10, 10);
linearLayout.setLayoutParams(layoutParams);

【讨论】:

    猜你喜欢
    • 2011-01-29
    • 2017-08-23
    • 2023-03-15
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    相关资源
    最近更新 更多