setSelection on Spinner based on rowId

前端 未结 7 705
离开以前
离开以前 2020-12-14 22:19

I have a Spinner View that\'s populated through a SimpleCursorAdapter.

Based on the selection I need to save the rowid in the entry database (posit

7条回答
  •  执笔经年
    2020-12-14 22:30

    If you want to set the selection of a Spinner thats backed by a CursorAdapter, you can loop through all the items in the Cursor and look for the one you want (assuming that the primary key in your table is named "_id"):

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    spinner.setAdapter(new SimpleCursorAdapter(...));
    
    for (int i = 0; i < spinner.getCount(); i++) {
        Cursor value = (Cursor) spinner.getItemAtPosition(i);
        long id = value.getLong(value.getColumnIndex("_id"));
        if (id == rowid) {
            spinner.setSelection(i);
        }
    }
    

    If you want to get the rowid of a selected item, you can do something similar:

    Cursor cursor = (Cursor) spinner.getSelectedItem();
    long rowid = cursor.getLong(cursor.getColumnIndex("_id"));
    

    There might be a quicker way to do it, but that's always worked for me.

提交回复
热议问题