Juholei
Juholei

Reputation: 25

Multiple buttons based on the same layout?

My app consists of GridLayout and multiple buttons (at the moment all of them are ToggleButtons). As the amount of buttons will change based on the user actions, I want to be able to add and remove the buttons in code. Can I create a layout for the button in xml and then create and add them to my GridLayout in Java?

Upvotes: 0

Views: 188

Answers (2)

Taldroid
Taldroid

Reputation: 380

you can do that easily. here's an example:

LinearLayout buttonsLayout = (LinearLayout) yourLayout.findViewById(R.id.items_layout);
LayoutParams buttonLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,         LayoutParams.WRAP_CONTENT);
buttonLayoutParams.setMargins(mMarginsInPixel, 0, mMarginsInPixel, 0);
button.setLayoutParams(buttonLayoutParams);

// Adding button to layout
buttonsLayout.addView(button);

// or removing button from layout
buttonsLayout.removeView(button);

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93559

Yes. Your getView function of your Adapter can inflate the button from xml. Generally you check and see if the incoming view is null, and if it is you inflate a new one.

Upvotes: 1

Related Questions