本文实例讲述了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;
}
@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程序设计有所帮助。
您可能感兴趣的文章:Android实现三级联动下拉框 下拉列表spinner的实例代码Android中Spinner(下拉框)控件的使用详解android 之Spinner下拉菜单实现级联Android Spinner 下拉菜单的使用Android自定义Spinner下拉列表(使用ArrayAdapter和自定义Adapter实现)Android实现下拉菜单Spinner效果Android UI组件Spinner下拉列表详解Android下拉列表spinner的实例代码android应用开发之spinner控件的简单使用Android控件Spinner的使用方法(1)