SetMargin Programmatically not working correctly for RelativeLayoutParams

I am currently programmatically adding a RelativeLayout encapsulated in Linearlayout. The base is a scrollview, and I'm trying to add these layouts to a scrollview called 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 relative layouts encapsulated in a horizontal layout with a horizontal orientation. I tried to give margins to each of the relative layers using setMargin with the right specific 5dp. However, this does not distinguish between the two relative markings. This worked if I did it manually in xml.

Differences can be seen in the image. the upper part is the layout specified in xml, and the two lower relative ones are generated programmatically

enter image description here

+4
source share
1 answer

decided my own.

The solution already exists! not enough google! my fault! Relative layout ignoring setMargin ()

+11
source

All Articles