本文執行個體講述了Android中Spinner控制項之索引值對用法。分享給大家供大家參考。具體如下:
一、字典表,用來存放索引值對資訊
package com.ljq.activity;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; }}
二、activity類,綁定資料、擷取選中的索引值對
package com.ljq.activity;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Spinner;import android.widget.Toast;import android.widget.AdapterView.OnItemSelectedListener;public class MainActivity extends Activity { private Spinner mySpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.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) { } }); }}
三、修改main.xml布局檔案
<?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>
四、運行結果如下:
希望本文所述對大家的Android程式設計有所協助。