Add margin programmatically to RelativeLayout
Got solution.
When you are using RelativeLayout
inside LinearLayout
, you need to use LinearLayout.LayoutParams
instead of RelativeLayout.LayoutParams
.
So replace your following code...
RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
relativeParams.setMargins(0, 80, 0, 0); // left, top, right, bottom
relativeLayout.setLayoutParams(relativeParams);
with...
// CODE FOR ADD MARGINS
LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearParams.setMargins(0, 80, 0, 0);
relativeLayout.setLayoutParams(linearParams);
relativeLayout.requestLayout();
You can use setMargins (int left, int top, int right, int bottom).
Try like this..
//CODE FOR ADD MARGINS
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
relativeParams.setMargins(0, 80, 0, 0);
relativeLayout.setLayoutParams(relativeParams);
Layout params should be set with resp to parentLayout .. in this case its LinearLayout
as rightly pointed by @ChintanRathod, so
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
will do the trick..
Be aware that you are using a relative layout inside a linear layout so you should use LinearLayout.LayoutParams
I would replace this :
//RELATIVE LAYOUT
RelativeLayout relativeLayout = new RelativeLayout(this);
relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT));
relativeLayout.setBackgroundColor(getResources().getColor(R.color.grayColor));
//CODE FOR ADD MARGINS
RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
relativeParams.topMargin=80;
relativeLayout.setLayoutParams(relativeParams);
by this :
//RELATIVE LAYOUT WITH PROPER LAYOUT PARAMS TO ADD MARGINS
RelativeLayout relativeLayout = new RelativeLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 80, 0, 0);
relativeLayout.setLayoutParams(params);
relativeLayout.setBackgroundColor(getResources().getColor(R.color.grayColor));
Note also that you should use WRAP_CONTENT
as height configuration for children in a vertical linearLayout. ( in FILL_PARENT
or MATCH_PARENT
mode it will fill the parent without leaving space for the other children)