【问题标题】:SetMargin Programmatically not working correctly for RelativeLayoutParamsSetMargin 以编程方式无法为 RelativeLayoutParams 正常工作
【发布时间】:2013-04-02 18:04:22
【问题描述】:

我目前正在以编程方式添加封装在 Linearlayout 中的 RelativeLayout。基础是一个滚动视图,我正在尝试将这些布局添加到名为 svbase 的滚动视图中

LinearLayout llbase = new LinearLayout(getApplicationContext());
 LinearLayout.LayoutParams llbaseParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // Verbose!
llbaseParams.setMargins(0, new CommonOpearation().getPixel(10, getApplicationContext()), 0,  new CommonOpearation().getPixel(10, getApplicationContext()));

llbase.setLayoutParams(llbaseParams);
llbase.setGravity(Gravity.CENTER_HORIZONTAL);

for(int n =0;n<2;n++)
{

  RelativeLayout rLayoutBase = new RelativeLayout(getApplicationContext());
  RelativeLayout.LayoutParams rLayoutParms = new RelativeLayout.LayoutParams( new CommonOpearation().getPixel(140, getApplicationContext()), new CommonOpearation().getPixel(125, getApplicationContext()));
  **rLayoutParms.setMargins(0, 0,  new CommonOpearation().getPixel(5, getApplicationContext()), 0);**
  rLayoutBase.setLayoutParams(rLayoutParms);


  Drawable drawable = MyCurrentActivity.this.getApplicationContext().getResources().getDrawable(R.drawable.curved_bg); //new Image that was added to the res folder
  try {
      rLayoutBase.getClass().getMethod(android.os.Build.VERSION.SDK_INT >= 16 ? "setBackground" : "setBackgroundDrawable", Drawable.class).invoke(rLayoutBase, drawable);
  } catch (Exception ex) {

  }

  llbase.addView(rLayoutBase);
} 

  svBase.addView(llbase);

如您所见,我有两个相对布局封装在水平方向的线性布局中。我已经尝试使用 setMargin 为每个相对布局提供边距,并且具有一定 5dp 的权利。但是,它不会在两个相对布局之间留出余量。不过,如果我要在 xml 中手动执行,它会起作用。

可以在图像中看到差异。顶部是一个 xml 指定布局,而底部两个相对布局是通过编程生成的

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    解决了我自己的问题。

    解决方案已经存在!谷歌不够!我的错! Relative Layout ignoring setMargin()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 2016-07-09
      • 2015-10-14
      相关资源
      最近更新 更多