Android beginner
Android beginner

Reputation: 245

Adding button dynamically to linear layout with id's?

Is there any way to add new buttons dynamically to linear layout with their unique id's. Considering a predefined button to perform this action.

Upvotes: 1

Views: 1114

Answers (2)

Mohammad Rababah
Mohammad Rababah

Reputation: 1726

LinearLayout row = new LinearLayout(this);
    row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
 Button btnTag = new Button(this);
        btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btnTag.setText("Button 1");
        btnTag.setId(1);
        row.addView(btnTag);
layout.addView(row);

Upvotes: 1

Kamlesh Meghwal
Kamlesh Meghwal

Reputation: 4982

Yes,you can dynamically add button to linear layout.

For Eg:

LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT,AbsListView.LayoutParams.WRAP_CONTENT));
layout.setId(5000);

Random random = new Random();
//Five button
for(int i=0;i<5;i++)
{
Button button = new Button(this);
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
button.setText("Button");
button.setId(random.nextInt(5)); //generate unique number between 0 to 4 and set it as id
layout.addView(button);
}

Upvotes: 0

Related Questions