How to dynamically change the Spinner's items

12,578

Solution 1

For the second spinner, use an Adapter over a List<String> (or whatever your City representation is). After changing the contents of the list, call notifyDataSetChanged on the adapter, and that will do.

Solution 2

You need to get a programmatic reference to the spinner, something like this:

     Spinner spinner = (Spinner) findViewById(R.id.spinner);
     ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.planets_array, android.R.layout.simple_spinner_item);
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     spinner.setAdapter(adapter);

Then to update your city's values, use an OnItemSelectedListener, like this:

public class MyOnItemSelectedListener implements OnItemSelectedListener {

   public void onItemSelected(AdapterView<?> parent,
      View view, int pos, long id) {
          //update content of your city spinner using the value at index,
          // id, or the view of the selected country. 
      }
   }

   public void onNothingSelected(AdapterView parent) {
   // Do nothing.
   }

}

Finally, you need to bind the listener to the country spinner like this:

    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

see here for reference: http://developer.android.com/resources/tutorials/views/hello-spinner.html

Share:
12,578

Related videos on Youtube

eros
Author by

eros

University student

Updated on June 04, 2022

Comments

  • eros
    eros about 2 years

    I have two spinners. Country and City. I want to dynamically change the City's values upon Country selection. I know how to create and initialize the values of Country but don't know how to set and change the City's values.

    Any guidance is appreciated.

    UPDATES1 The problem is, I don't have idea on how to update the content of City Spinner. I know listener and other basics on how to create a fixed spinner.

  • eros
    eros almost 13 years
    would you share on how to update content of your city spinner?
  • K-ballo
    K-ballo almost 13 years
    @eros: Sure, adapter.notifyDataSetChanged();
  • eros
    eros almost 13 years
    "Notifies the attached View that the underlying data has been changed and it should refresh itself." <- 1) its automatically refresh? 2) do I need to declare my adapter as Activity instance variable?
  • eros
    eros almost 13 years
    I declare my City's adapter as Activty's instance variable. Then utilize, clear() & add().Afterwards, call adapter.notifyDataSetChanged(). If you have better approach, please share it here.