anroid开发教程之spinner下拉列表的使用示例
首先在xml文件添加spinner控件:
<spinner
android:id="@+id/myspinner"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
在activity中写:
package com.example.spinner;
import android.app.activity;
import android.os.bundle;
import android.view.view;
import android.widget.adapterview;
import android.widget.adapterview.onitemselectedlistener;
import android.widget.arrayadapter;
import android.widget.spinner;
import android.widget.toast;
public class mainactivity extends activity {
private spinner spinner;
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
spinner = (spinner)this.findviewbyid(r.id.myspinner);
//设置数据源
string[] mydata = {"北京", "上海","广东","广西"};
//声明一个arrayadapter,并将数据源与之关联起来
arrayadapter<string> adapter = new arrayadapter<string>(this,android.r.layout.simple_spinner_item,mydata);
//设置弹出下拉列表的风格
adapter.setdropdownviewresource(android.r.layout.simple_spinner_dropdown_item);
//将arrayadapter对象添加进spinner去
spinner.setadapter(adapter);
//添加监听器
spinner.setonitemselectedlistener(new onitemselectedlistener() {
@override
public void onitemselected(adapterview<?> arg0, view arg1,
int arg2, long arg3) {
toast.maketext(mainactivity.this, "选择了:" + arg2, toast.length_short).show();
}
@override
public void onnothingselected(adapterview<?> arg0) {
// todo auto-generated method stub
}
});
}
}