我目前正在以编程方式添加封装在 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 指定布局,而底部两个相对布局是通过编程生成的