用法这是一个老问题,但第一个搞清楚这个问题时,我发现。这里有一个详细的解释,全面的来源可能会削减一些legwork。
答案是确实使用它处理字符串列表的SimpleCursorAdapter,但也有在选择的行获取返回匹配ID字段进行特殊处理。以使这项工作的关键是要知道的信息,以下两个不起眼位:
1)在创建光标确保查询返回名为“_id”的字段。这个字段不需要显示在任何地方,但是当选择列表项时它的值将被传回。
2)创建SimpleCursorAdapter时,需要提供将放置行文本的TextView布局ID。如果使用android提供的布局android.R.layout.simple_spinner_item,则需要使用的文本ID是android.R.id.text1。
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);
// 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) {}
});
}
}
[你可以在这里看到](http://samir-mangroliya.blogspot.in/2012/09/android-populate-spinner-from-sqlite.html) – 2012-10-17 06:16:50