Setting ID for Spinner items

后端 未结 5 2073
温柔的废话
温柔的废话 2020-12-25 12:50

I have an array of Strings I\'m populating a Spinner object with. However, I\'d like to attach an ID to each element of the Spinner, so when the user selects an item, I hav

5条回答
  •  抹茶落季
    2020-12-25 13:20

    What do you mean by id. You can use ArrayAdapter to populate the Spinner. When item is selected just get the element from the adapter and save the data you want.

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter adapter = ... // initialize the adapter
    adapter.setDropDownViewResource(android.R.layout.some_view);
    spinner.setAdapter(adapter);
    

    and when item is selected

    public void onItemSelected(AdapterView parent, View view, int pos, long id) {
        MyObject selected = parent.getItemAtPosition(pos);
        // save any data relevant with selected item   
    }
    

    If you are storing your data in db you can use CursorAdapter and in onItemSelected to fetch the selected item id from the cursor.

提交回复
热议问题