In my application, I have a layout which has a RelativeLayout to which I want to set margins at runtime programmatically. But when I do that, it gives me
Try setting FrameLayout.LayoutParams instead if RelativeLayout.LayoutParams. When you set the layout params at runtime, you have to set the ones from it's parent.
So, it'll be:
FrameLayout.LayoutParams _rootLayoutParams = new FrameLayout.LayoutParams(_rootLayout.getWidth(), _rootLayout.getHeight());
_rootLayoutParams.setMargins(300, 0, 300, 0);
_rootLayout.setLayoutParams(_rootLayoutParams);
I suggest that the parent of the @id/rl_root must be FrameLayout which is not showing in this xml. LayoutParam's type should be the same with its parent not itself.
I've had this error once before and it was because I tried to cast the parameters instead of creating a new instance. I hope this helps.
Right here :
RelativeLayout.LayoutParams _rootLayoutParams = new RelativeLayout.LayoutParams(_rootLayout.getWidth(), _rootLayout.getHeight());
Should be:
RelativeLayout.LayoutParams _rootLayoutParams = new RelativeLayout.LayoutParams(_rootLayout.getLayoutParams());
Now that you have all the layout parameters from the parent (root) layout, you can use them to set the parameters for your child view that you are inflating.
// Example usage:
// viewGroup is the parent in this case whose parameters we want as a reference point.
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(viewGroup.getLayoutParams());
// Now we can add a rule stating that we want to center our new view both horizontally and vertically in the parent (viewGroup) view.
params.addRule(RelativeLayout.CENTER_IN_PARENT);
// Add more rules here if you would like
params.addRule(newRule2);
// After all of your new parameters are laid out, assign them to the view you want them applied to
newView.setLayoutParams(params);
// Add the view to your hierarchy and enjoy
viewGroup.addView(newView);