这是一个老问题,但我在解决这个问题时发现的第一个问题。这是完整来源的详细解释,可能会减少一些跑腿工作。
答案确实使用SimpleCursorAdapter,它处理字符串列表,但也具有特殊处理,适用于选择行时返回的匹配ID字段。完成这项工作的关键是了解以下两个晦涩难懂的信息:
1) 创建游标时,确保查询返回标题为“_id”的字段。此字段不需要显示任何位置,但选择列表项时,它的值将传递回来。
2) 创建 SimpleCursorAdapter 时,您需要提供将放置行文本的 TextView 布局 ID。如果使用 android 提供的布局 android.R.layout.simple_spinner_item,您需要使用的文本 id 是 android.R.id.text1。
主.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);
// just for this example:
// create database table with an id field and a text field and add some data
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();
// get a cursor from the database with an "_id" field
Cursor c = db.rawQuery("SELECT someIDF AS _id, someTextF FROM someTable", null);
// make an adapter from the cursor
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);
// set layout for activated adapter
sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// get xml file spinner and set adapter
Spinner spin = (Spinner) this.findViewById(R.id.spinner1);
spin.setAdapter(sca);
// set spinner listener to display the selected item id
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) {}
});
}
}