Search code examples
androidandroid-relativelayoutpaddingmargins

RelativeLayout programmatically margins not working


    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.


Solution

  • 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));