安卓Spinner用法最簡單獲取鍵值對
public class MainActivity extends Activity {
private Spinner mySpinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySpinner = (Spinner) findViewById(R.id.mySpinner);
List<Dict> dicts = new ArrayList<Dict>();
dicts.add(new Dict(1, "測試1"));
dicts.add(new Dict(2, "測試2"));
dicts.add(new Dict(3, "測試3"));
dicts.add(new Dict(4, "測試4"));
ArrayAdapter<Dict> adapter = new ArrayAdapter<Dict>(this,
android.R.layout.simple_spinner_item, dicts);
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// 獲取鍵的方法:mySpinner.getSelectedItem().toString()或((Dict)mySpinner.getSelectedItem()).getId()
// 獲取值的方法:((Dict)mySpinner.getSelectedItem()).getText();
Toast.makeText(MainActivity.this,
"鍵:" + mySpinner.getSelectedItem().toString() + "、" + ((Dict) mySpinner.getSelectedItem()).getId() +
",值:" + ((Dict) mySpinner.getSelectedItem()).getText(),
Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
package com.example.demo9_spinner;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Dict implements Serializable{
private Integer id;
private String text;
public Dict() {
}
public Dict(Integer id, String text) {
super();
this.id = id;
this.text = text;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
/**
* 為什麼要重寫toString()呢?
*
* 因為介面卡在顯示資料的時候,如果傳入介面卡的物件不是字串的情況下,直接就使用物件.toString()
*/
@Override
public String toString() {
return text;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Spinner android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mySpinner"/>
</LinearLayout>