jrharshath
jrharshath

Reputation: 26583

displaying objects in a spinner rather than just strings

I'm building a dialog with a spinner. When the dialog is done, it calls a method of the parent activity with a string argument - the argument being the string value that was selected.

My current approach:
I'm setting up the spinner's array adapter like so:

ArrayAdapter<String> adapter = 
    new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,
    categoryNames);     

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);

categoryNames is a string array. When the dialog is done, the selected categoryName is used as the parameter to the method call on the parent activity.

What I really want to do:
What I actually want is to display a list of Category objects. The Category class has 2 properties - categoryId and categoryName. The spinner should still display the categoryNames in the drop-down view, but when the dialog is done, it should be able to unambiguously tell which Category was selected, and call the parent activity's callback method with the categoryId of the category that was selected.

There can be multiple Categoryies with the same categoryName.

Question: How to do the above?

Upvotes: 0

Views: 3257

Answers (1)

Sam
Sam

Reputation: 86948

There are a couple different way to do what you want:

  • Store the extra data in the adapter, like a SimpleAdapter, SimpleCursorAdapter, or custom one.
  • Use a Collection of custom objects instead of Strings, simply override the toString() method to present user readable Strings in the Spinner.

You seem to want to do the second option, so here's a generic example:

class Category {
    int id;
    String name;

    public Category(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

Your ArrayAdapter is almost the same:

List<Category> categories = new ArrayList<Category>();
// Add new items with: categories.add(new Category(0, "Stack");

ArrayAdapter<Category> adapter = 
        new ArrayAdapter<Category>(getActivity(), android.R.layout.simple_spinner_item,
        categories);

...
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Category category = parent.getItemAtPosition(position);
        Log.v("Example", "Item Selected id: " + category.id + ", name: " + category.name);
    }

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

Upvotes: 10

Related Questions