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

eri*_*lee 4 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);
Run Code Online (Sandbox Code Playgroud)

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

可以在图像上看到差异.top是xml指定布局,而bottom 2 relativelayout是以编程方式生成的

在此输入图像描述

eri*_*lee 10

解决了我自己.

解决方案已经存在!没够谷歌!我的错! 相对布局忽略setMargin()