Arpit Garg
Arpit Garg

Reputation: 8546

Problem in Spinner Item List

In android Can I have a Spinner with some categories and some sub items added to them.

For example say I select a country then specific cities are shown for selection.

Please help me

Upvotes: 0

Views: 634

Answers (1)

erichamion
erichamion

Reputation: 4537

If you have two spinners, you can fill one when a selection is made in the other. An OnItemSelectedListener would be good for this purpose. Something like the following might work, although I haven't tested this, so it may contain errors. Even if it works, not everything may be done in the best possible way.

final HashMap<String, ArrayList<String>> optionsForCategories;
final Spinner categorySpinner;
final spinner individualSpinner;
final ArrayAdapter<String> individualSpinnerAdapter;

...

categorySpinner.setOnItemSelectedListener(new OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, 
            int position, long id) {
        String selectedCategory = parent.getItemAtPosition(position);
        individualSpinnerAdapter.clear();
        individualSpinnerAdapter.addAll(optionsForCategories.get(selectedCategory);
    }

    public void onNothingSelected(AdapterView<?> parent) { }
});

It would be perfectly natural and expected to have two spinners. However, if you really want only one (which isn't clear, but seems to be implied in your question), then you might show a dialog from the spinner's OnItemSelectedListener.

Upvotes: 2

Related Questions