Note that there are some explanatory texts on larger screens.

plurals
  1. POAdd an array of buttons to a GridView in an Android application
    text
    copied!<p>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.</p> <p>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 <a href="http://developer.android.com/guide/samples/ApiDemos/res/values/arrays.html" rel="noreferrer">arrays.xml</a>, 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.</p> <p><strong>Update - Added info about adding to a GridView</strong></p> <p>I want to add this to a GridView, so calling the [addView method](<a href="http://developer.android.com/reference/android/widget/AdapterView.html#addView(android.view.View,%20int)" rel="noreferrer">http://developer.android.com/reference/android/widget/AdapterView.html#addView(android.view.View,%20int)</a> results in an UnsupportedOperationException. I can do the following:</p> <pre><code>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); </code></pre> <p>but that doesn't layout the buttons in a grid like I would like. Can this be done in a GridView?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload