How to set RelativeLayout layout params in code not in xml?
android, android-layout, android-relativelayout
Solution
Just a basic example:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
Button button1;
button1.setLayoutParams(params);
params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
Button button2;
button2.setLayoutParams(params);
As you can see, this is what you have to do:
- Create a `RelativeLayout.LayoutParams` object.
- Use `addRule(int)` or `addRule(int, int)` to set the rules. The first method is used to add rules that don't require values.
- Set the parameters to the view (in this case, to each button).
Problem
For example I want to add 3 buttons on screen: one align left, one align center, last one align right. How can I set their layout in code, not in `xml`?