SetMargin以编程方式无法正常运行RelativeLayoutParams

时间:2013-04-02 18:04:22

标签: android android-layout

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

的scrollview中
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);

正如你所看到的,我有两个relativelayout封装在linearlayout中,水平方向。我尝试使用setMargin为每个relativelayout提供保证金,权利为某个5dp。然而,它没有在两个相对布局之间给出边距。如果我在xml手动完成它,它会工作。

可以在图像上看到差异。 top是一个xml指定布局,而底部两个relativelayout是以编程方式生成的

enter image description here

1 个答案:

答案 0 :(得分:11)

解决了我自己。

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