这是一个老问题,但当我解决此问题时找到的第一个问题。这里有一个详细的解释和完整的源代码,可以减少一些工作量。
答案确实是使用SimpleCursorAdapter,它处理字符串列表,但同时也具有特殊处理匹配ID字段的功能,该字段在选择行时返回。使其工作的关键在于了解以下两个模糊信息:
1)在创建游标时,请确保查询返回一个名为“_id”的字段。此字段无需显示在任何位置,但在选择列表项时将传递其值。
2)在创建SimpleCursorAdapter时,您需要提供TextView布局ID,用于放置行文本。如果使用Android提供的布局android.R.layout.simple_spinner_item,则需要使用android.R.id.text1作为文本ID。
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Spinner
android:id="@+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
></Spinner>
</RelativeLayout>
活动代码:
public class TesterActivity extends Activity {
public Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
class MyDBHelper extends SQLiteOpenHelper {
public MyDBHelper(Context context) {
super(context, "someDB", null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE someTable (someIDF INTEGER, someTextF TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS someTable");
onCreate(db);
db.execSQL("INSERT INTO someTable (someIDF, someTextF) VALUES (54, 'Some text')");
db.execSQL("INSERT INTO someTable (someIDF, someTextF) VALUES (99, 'Some more text')");
db.execSQL("INSERT INTO someTable (someIDF, someTextF) VALUES (173, 'Even more text')");
}
}
SQLiteDatabase db = new MyDBHelper(this).getWritableDatabase();
Cursor c = db.rawQuery("SELECT someIDF AS _id, someTextF FROM someTable", null);
String[] from = new String[] {"someTextF"};
int[] to = new int[] {android.R.id.text1};
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to);
sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spin = (Spinner) this.findViewById(R.id.spinner1);
spin.setAdapter(sca);
mContext = this;
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
Toast.makeText(mContext, "Selected ID=" + id, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {}
});
}
}