Skip to content Skip to sidebar Skip to footer

Affect Second Spinner Choices Based On First Spinner

So I can see that there are questions about this, but not in the scope of mine. I am buliding an app for Android that has two spinners. The first has an array of choices. However,

Solution 1:

Try this,

firstSpinner.setOnItemSelectedListener(newOnItemSelectedListener() {

            @OverridepublicvoidonItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stubstring selectedValue = arg0.getSelectedItem().toString();
                    if(selectedValue.equalsIgnoreCase(string1)
                    {
                        ArrayAdapter<String> firstAdapter = newArrayAdapter<String>(this,
                            android.R.layout.simple_list_item_1, firstArray);

                        secondSpinner.setAdapter(firstAdapter);//
                    }

                   elseif(selectedValue.equalsIgnoreCase(string2)
                   {
                      ArrayAdapter<String> firstAdapter = newArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array2);

                      secondSpinner.setAdapter(firstAdapter);

                   }
            }

Hope it will help you.

Solution 2:

If it's a String array you could define it in XML then use getResource().getStringArray() or declare it in Java.

In your listener for the first spinner, you could do the following to set the choices for the second spinner.

secondSpinnerAdapter = newArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, newArray);
secondSpinner.setAdapter(secondSpinnerAdapter);

Tested and working

Solution 3:

update the array list of second spinner in 1st spinner setOnItemSelectedListener

spinner1.setOnItemSelectedListener(newOnItemSelectedListener() {

            @OverridepublicvoidonItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stubstring str=spinner1.getSelectedItem().toString();
                    if(str.equals("spinner item"))//spinner item is selected item of spinner1
                    {
                        ArrayAdapter<String>adapter1 = newArrayAdapter<String>(this,
                            android.R.layout.simple_list_item_1, array1);
                 //adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                 spinner2.setAdapter(adapter1);//
                    }elseif{
                   ArrayAdapter<String>adapter1 = newArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array2);
                    //adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
                 spinner2.setAdapter(adapter2);

        }
            }

Post a Comment for "Affect Second Spinner Choices Based On First Spinner"