RelativeLayout programmatically margins not working

607 views Asked by At
    LinearLayout usersPlaceholder = Main.lay_found_users;   //Found Users Placeholder

    //RelativeLayout Params
    RelativeLayout userlay = new RelativeLayout(mCtx);      //Create new Element
    userlay.setBackgroundResource(R.drawable.btn_useritem); //Background
    userlay.setGravity(RelativeLayout.CENTER_HORIZONTAL);   //Gravity
    userlay.setClickable(true);                             //Clickable

    RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, dp(80));
    relativeParams.setMargins(dp(80), dp(80), dp(80), dp(80));
    userlay.setLayoutParams(relativeParams);
    userlay.requestLayout();
    usersPlaceholder.addView(userlay);

Margins are not setting. The RelativeLayout which is the child element, is expanding until match the parent usersPlaceholder which is a LinearLayout. I also tried setting paddings to the parent element but the same problem...

This method transforms the measures

    public int dp(int dps){
    final float scale = mCtx.getResources().getDisplayMetrics().density;
    return (int) (dps * scale + 0.5f);
}

Main Activity:

public class Main extends Activity{

   Context ctx;
   public static LinearLayout lay_found_users;

   @Override
   protected void onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      setContentView(R.layout.act_main);

      lay_found_users = (LinearLayout) findViewById(R.id.lay_found_users);
   }
}

Suggestions? Thanks.

2

There are 2 answers

0
Joakim On BEST ANSWER

Both LinearLayout.LayoutParamsand RelativeLayout.LayoutParams extends MarginLayoutParams, which explains why some settings apply for both Layouts. If you set a parameter that is not available in the layout, it's simply ignored.

When using RelativeLayout, I would use padding instead of margins. It might solve your problem.

Padding is set directly on the view, and not on the LayoutParams. So for example: userLay.setPadding(dp(80),dp(80),dp(80),dp(80));

0
ProtectedVoid On

I've found a solution, but I don't understand it. I made the margins work, creating LayoutParams from LinearLayout this way:

LinearLayout.LayoutParams relativeParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp(80));

I don't get it because I've created a new RelativeLayout:

RelativeLayout userlay = new RelativeLayout(mCtx);

I'm applying LinearLayout parameters to a RelativeLayout

Layout types don't match but params work. Can someone tell me why? Thanks.