Android中Spinner控件之键值对用法实例分析
程序员文章站
2023-11-27 18:50:04
本文实例讲述了android中spinner控件之键值对用法。分享给大家供大家参考。具体如下:
一、字典表,用来存放键值对信息
package com.ljq....
本文实例讲述了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程序设计有所帮助。