开发者

Android Bind Spinner to Class

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);       
 Ar开发者_JAVA技巧rayAdapter<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.


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.


very old post -- just came across looking for something else -- noiced a mistake (probably just oversight)

jagsund is mostly right, accept, he got the definion of getView and GetDropDownView wrong - its actually the opposite of what he said : getView shows the content inside the spinner control, getDropDownView creates the view rows that you see when you click on the spinner.

So, unless you click on the spinner, getDropDownView will not even get called - you'll see this if you override ArrayAdapter

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜