views:

533

answers:

1

I'm having some trouble with the Spinner widget. Given the following code:

    ArrayList<Person> people= new ArrayList<Person>();

    Person = null;
    for(int i = 0; i!= 10; i++) {
        p = new Person();
        s.setID(i);
        s.setName("Name " + i);
        people.add(s);
    }

I'm using the following code to bind it to a Spinner:

 Spinner spinner1 = (Spinner) findViewById  (R.id.spinner);       
 ArrayAdapter<Person> adapter = new ArrayAdapter<Person>(this, android.R.layout.simple_spinner_item, people);                           
 spinner1.setAdapter(adapter);  

What I would like is for the value (id) to be hidden but passed when selected, and the name to appear. Any help is appreciated.

Thanks.

+3  A: 

If I understand your question correctly you would like the name to appear in the spinner dropdown view. When an item is selected you would like to return the id.

There are 2 ways you can approach this.

The simplest way is to implement a toString() that returns the name in your Person object. The ArrayAdapter will return this value when binding the text values of your object to the dropdown view. Then in your activity you can set the onItemClickListener for the Spinner and call on the adapter.getItemAtPosition(position) to retrieve the Person object. From that person object you can get your id.

The second approach is to extend the ArrayAdapter and implement the getView and getDropDownView and getItem methods. The getView is responsible for creating the rows you see when you click the spinner. The getDropDownView is responsible for creating the view you see in the spinner. And the getItem method will return the object or in your case the id at that specified position. You should bind the name of the Person element to a textview in your getView and getDropDownView methods. After you've created your custom ArrayAdapter you should set the onItemClicKListener for the Spinner and handle it just as I have mentioned above.

The first approach is simple but the second approach is far superior and will yield much greater control over your adapter, especially when you begin to develop something much more complex.

Hope that helps.

jagsaund
I get the theroy, but I'm having trouble with the implementation. Do you have any code to help me along the way?
drbob