Vedran Kopanja
Vedran Kopanja

Reputation: 1299

Spinners with same ID/How to add rows programmatically

I'm having an issue with an app I'm developing. I have a screen with a starting spinner (choosing clients) and 1 row with elements inside. When I click the plus button it adds more of those rows. The problem is because I'm adding them with XML layout file I can't change the ID (or can I?). So I can't take the values from each of them, even the onItemSelected works for the clients spinner but not for the others. I got a screenshot of the screen here and a code snippet for creating first row/other rows.

Screenshot: http://dl.dropbox.com/u/9667835/Screenshot_2012-11-14-10-44-38.png

private void startRow()
{
    ArrayAdapter<String> adapterUnits = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item);
    for(int i=0; i<units_arr.size(); i++)
        adapterUnits.add(units_arr.get(i).get("name").toString());
    ArrayAdapter<String> adapterVats = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item);
    for(int i=0; i<vats_arr.size(); i++)
        adapterVats.add(vats_arr.get(i).get("value").toString());

    tl = (TableLayout) findViewById(R.id.add_invoice_layout);
    LayoutInflater inflater = LayoutInflater.from(this);
    View item = inflater.inflate(R.layout.add_invoice_row, tl, false);

    Spinner units = (Spinner) item.findViewById(R.id.spinnerUnit);
    Spinner vats = (Spinner) item.findViewById(R.id.spinnerVAT);
    units.setAdapter(adapterUnits);
    vats.setAdapter(adapterVats);
    tl.addView(item);
}

Upvotes: 2

Views: 453

Answers (1)

Daniel
Daniel

Reputation: 3806

Keep a reference to each inflated view and then iterate those when you handle the finished input data;

// View references, as a class property
private ArrayList<View> viewRef = new ArrayList<View>();

View item = inflater.inflate ...
this.viewRef.add(item);

Now, when the data is to be processed you do as such;

for (View item : this.viewRef)

ID's are supposed to be unique, so you should use tags instead. See findViewWithTag

Edit; If you do not want to store references to the views manually you could iterate them using the getChildCount() method of the parenting View;

for (int i = 0; i < parent.getChildCount(); i++)
{
     View item = (View) parent.getChildAt(i);
}

Upvotes: 1

Related Questions