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