以编程方式设置相对布局参数的边距无法正常工作

4

我目前正在以编程方式添加RelativeLayout,该RelativeLayout被封装在LinearLayout中。 基础是一个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);

如您所见,我有两个相对布局封装在具有水平方向的线性布局中。我尝试使用setMargin为每个相对布局提供一定5dp的右边距。但是,它不会在两个相对布局之间提供边距。如果我在xml中手动操作,则可以正常工作。如图所示,可以看到差异。顶部是一个xml指定的布局,而底部的两个相对布局是以编程方式生成的。
1个回答

10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接