Add an array of buttons to a GridView in an Android application

Posted by Tai Squared on Stack Overflow See other posts from Stack Overflow or by Tai Squared
Published on 2009-04-21T23:56:50Z Indexed on 2010/03/31 6:53 UTC
Read the original article Hit count: 1210

Filed under:
|
|
|

I have an application that will have 5-15 buttons depending on what is available from a backend. How do I define the proper GridView layout files to include an array of buttons that will each have different text and other attributes? Each button will essentially add an item to a cart, so the onClick code will be the same except for the item it adds to the cart.

How can I define an array so I can add a variable number of buttons, but still reference each of them by a unique ID? I've seen examples of the arrays.xml, but they have created an array of strings that are pre-set. I need a way to create an object and not have the text defined in the layout or arrays xml file.

Update - Added info about adding to a GridView

I want to add this to a GridView, so calling the addView method results in an UnsupportedOperationException. I can do the following:

ImageButton b2 = new ImageButton(getApplicationContext());
b2.setBackgroundResource(R.drawable.img_3);
android.widget.LinearLayout container = (android.widget.LinearLayout) findViewById(R.id.lay);
container.addView(b2);

but that doesn't layout the buttons in a grid like I would like. Can this be done in a GridView?

© Stack Overflow or respective owner

Related posts about android

Related posts about button