设置ID为微调物品物品、ID

2023-09-04 12:32:28 作者:弱者才群居

我有串,我填充了微调对象的数组。但是,我想的ID附加到微调的每个元件,所以当用户选择一个项目,我有其ID用于保存到一些其它数据片段。我怎样才能做到这一点?

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 have its ID to use to save to some other piece of data. How can I do this?

推荐答案

你说的ID的意思。您可以使用ArrayAdapter来填充微调。当项目被选中刚刚获得来自适配器的元素,并保存您想要的数据。

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<MyObject> adapter = ... // initialize the adapter
adapter.setDropDownViewResource(android.R.layout.some_view);
spinner.setAdapter(adapter);

和项目时,选择

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

如果你正在将数据存储到数据库,你可以使用的CursorAdapter和onItemSelected从游标提取所选择的项目ID。

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