Monday, December 9, 2013

Add Views programmatically

Example of adding two Buttons in a RelativeLayout :

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(
                   LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

RelativeLayout.LayoutParams b4_lp = new RelativeLayout.LayoutParams(
                  LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
b4_lp.addRule(RelativeLayout.RIGHT_OF, b3.getId());

layout.addView(b3, b3_lp);
layout.addView(b4, b4_lp);


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.

No comments:

Post a Comment