Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetMargin Programmatically not working correctly for RelativeLayoutParams

I'm currently programmatically adding RelativeLayout encapsulated in a Linearlayout. The base is a scrollview and i'm trying to add those layouts into scrollview named 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);

As you can see I have two relativelayout encapsulated in the linearlayout with a horizontal orientation. I've tried giving margin to each of the relativelayout using setMargin with a right of certain 5dp. However it does not gives margin inbetween the two relativelayout. It worked if I were to do in manually in xml though.

The differences can be seen at the image. the top is a xml specify layout while the bottom two relativelayout are generated programmatically

enter image description here

like image 475
ericlee Avatar asked Dec 27 '22 06:12

ericlee


1 Answers

solved my own.

The solution is already out there! did not google enough! my fault! Relative Layout ignoring setMargin()

like image 61
ericlee Avatar answered Feb 08 '23 23:02

ericlee