eros
eros

Reputation: 5076

How to dynamically change the Spinner's items

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.

Upvotes: 5

Views: 13037

Answers (2)

RestingRobot
RestingRobot

Reputation: 2978

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

Upvotes: 3

K-ballo
K-ballo

Reputation: 81349

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.

Upvotes: 6

Related Questions