Frage

The user enters a number in an EditText, the app then programmatically creates that many spinners. I am having problems getting the positions of those spinners to save them when the user clicks the "save" button at the bottom of my UI.

When I try to get the position with: mArraySpinner.add(spinner.getSelectedItemPosition()); as seen below I have several empty locations in the array like the listener is firing on creation and then it will only save the last spinners position in the last element of the array.

Here is the code that I create the spinners with:

for(int i = 1; i <= numStockTanks; i++) {
        TableRow tR = new TableRow(this);
        // creates the textView
        tV1 = new TextView(this);
        tV1.setText("Stock Tank #" + i + " size: ");

        // add spinner to row
        spinner = new Spinner(this);
        ArrayAdapter<CharSequence> adapterStockTankSize = ArrayAdapter.createFromResource(
                this, R.array.StockTankSize, android.R.layout.simple_spinner_item);
        adapterStockTankSize.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapterStockTankSize);
        spinner.setTag(i + 600);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onNothingSelected(AdapterView<?> parent) {}
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                mArraySpinner.add(spinner.getSelectedItemPosition());
            }
        });

        // add the TextView and the editText to the new TableRow
        tR.addView(tV1);
        tR.addView(spinner);

        // add the TableRow to the TableLayout
        tL.addView(tR,new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));    
    } // end for statement

thanks for your help

War es hilfreich?

Lösung

You are reassigning the spinner variable each time, but the onItemSelected method is using this variable. You need to redeclare this spinner variable each time so that the method is looking for a unique Spinner object.

Change spinner = new Spinner(this); to final Spinner spinner = new Spinner(this);, and remove whatever declaration of spinner you have already.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top