1) Instantiate the RelativeLayout
2) Instantiate the Buttons.
3) Create the LayoutParams for each Buttons.
4) Add Views to their parent. That's the RelativeLayout.
One key point here. The LayoutParams for the child Views must the same type as that of their parent. So in our case both Buttons LayoutParams have to be RelativeLayout.LayoutParams.
Let's see how this applies to code :
RelativeLayout layout = new RelativeLayout(this); // Instantiate the parent
b3 = new Button(this); b3.setId(1);
b3.setText("Relative Button 3");
b4 = new Button(this); b4.setId(2);
b4.setText("Relative Button 4");
RelativeLayout.LayoutParams b3_lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams b4_lp = new RelativeLayout.LayoutParams(
The result is :
Notice the addRule() which sets the Button b4 to the right of the b3.
To achieve that we have to set Id's for our Buttons so we can refer to the view that acts as an anchor.