0

I want to have dynamic spinner in android e.g one spinner for country and depending upon the value selected in Country, i want to get another spinner for states.

Ranjeet
  • 19
  • 1
  • 6

1 Answers1

3

I believe you can solve this with the OnItemSelectedListener.

public void onCreate() {
     ....
    Country[] mCountries = ... ;
    final Spinner spinner1 = ...;
    final Spinner spinner2 = ...;

    spinner1.setAdapter(new ArrayAdapter(mCountries);
    spinner1.setOnItemSelectedListener( new OnItemSelectedListener() {

    void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Country country = (Country) parent.getAdapter().getItem(position);
        spinner2.setAdapter(new ArrayAdapter(country.getStates());
     }
     void onNothingSelected(AdapterView<?> parent) {
        spinner2.setAdapter(null);
     }
    });
 ....
}
Greg Giacovelli
  • 10,164
  • 2
  • 47
  • 64
  • Thanks Greg for your help. But what if the number of spinner keeps growing dynamically. e.g if we select states then we should have another spinner for district and so on. – Ranjeet Oct 21 '10 at 10:05
  • Hi Ranjeet, you can probably just use a list of spinners and apply the same algorithm in a loop. The list should be ordered by most general spinner to most specific. Or you could even create the new spinner and add it to the view hierarchy within your on item selected listener. – Greg Giacovelli Oct 21 '10 at 15:53
  • Thanks again Greg. This is what I was looking for. One more help please. Can we have more than 1 value associated with Spinner. e.g. can we have Spinner having country and its countrycode as its id. This is just like our normal html way. – Ranjeet Oct 22 '10 at 08:51
  • When you are creating the spinner you can probably call setTag on the newly created spinner and pass the appropriate country code as the value. Then you should be able to read that out via getTag – Greg Giacovelli Oct 23 '10 at 07:32
  • Greg, is there any way that by default nothing is selected in our Spinner? – Ranjeet Oct 27 '10 at 13:05
  • Oh course :) You could make something like, Country.NONE("Please select a valid Country"), or use null as an element of the array of countries. Then inside of the first spinner's onSelectedItemListner, if the value selected is null, then remove all other spinners. This pattern can be repeated for the last ones too. (This is starting to get rather involved). – Greg Giacovelli Oct 28 '10 at 06:43