kyuu
kyuu

Reputation: 237

Add Button in Relative Layout

I want to add some button in a Sliding Drawer's content, its content is a Relative Layout. The button will be defined in Java code and the Relative Layout is already defined in xml layout. So, let's say i want to add 4 buttons:

for (int i=0; i<4; i++) {
     Button btn = new Button(this);
     btn.setId(i);
     btn.setText("some_text");
}

Then i initialize the Relative Layout:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.slidingDrawerContent);

Now how do i add all of the Button into the Relative Layout? Thanks for the help.

Upvotes: 1

Views: 4535

Answers (2)

Dheeresh Singh
Dheeresh Singh

Reputation: 15701

RelativeLayout layout = (RelativeLayout)findViewById(R.id.slidingDrawerContent);
for (int i=0; i<4; i++) {
     Button btn = new Button(this);
     btn.setId(i);
     btn.setText("some_text");
    layout.add(btn); 
}

or

a bit advance

 RelativeLayout layout = (RelativeLayout)findViewById(R.id.slidingDrawerContent);
 RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT );


    for (int i=0; i<4; i++) {
         Button btn = new Button(this);
         btn.setId(i);
         btn.setText("some_text");

        // lp.addRule(RelativeLayout.RIGHT_OF, <Id>);

         layout.addView(tv2, lp); 
    }

Upvotes: 3

Zaz Gmy
Zaz Gmy

Reputation: 4356

simply do this:

layout.addView(btn);

Upvotes: 0

Related Questions