新建一个Android项目,在main.xml中输入如下代码(注意要把我注释去掉,否则会报错):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" > //组件水平摆放
<Spinner
android:id="@+id/city" //一级栏目
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:prompt="@string/city_promt"
android:entries="@array/city_lables"/>
<Spinner
android:id="@+id/area" //二级栏目
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:prompt="@string/city_promt"/> //提示信息
</LinearLayout>
在strings.xml中输入:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, MySpinnerListenerDemo!</string>
<string name="app_name">下拉列表宽事件</string>
<string name="city_promt">选择您喜欢的城市</string>
<string name="area_promt">选择您喜欢的城区</string>
</resources>
由于一个城市会有多个城区,那么下面为了简单起见,定义一个数值,通过数组来保存着若干个城区,而在实际之中肯定需要单独的数据提供了。
在MySpinnerListenerDemo.java中输入如下代码(注意不同的包,否则会报错):
package com.tarena.spinnerlistener;
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;
public class MySpinnerListenerDemo extends Activity {
private Spinner city = null; //下拉列表框的内容
private Spinner area = null; //二级列表
private String[][] areaData = new String[][]{
{"海城区","银海区","铁山港区"},
{"秀峰区","七星高新区","叠彩区","象山区"},
{"西乡塘区","兴宁区","江南区","青秀区","良庆区","邕宁区"}}; //子菜单项
private ArrayAdapter<CharSequence> adapterArea = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.main);
this.city = (Spinner) super.findViewById(R.id.city); //取得下拉列表框
this.area = (Spinner) super.findViewById(R.id.area); //取得下拉列表框
this.city.setOnItemSelectedListener(new OnItemSelectedListenerImpl());
}
private class OnItemSelectedListenerImpl implements OnItemSelectedListener{
public void onItemSelected(AdapterView<?> parent, View view,
int position,long id) { //表示选项改变的时候触发
MySpinnerListenerDemo.this.adapterArea = new ArrayAdapter<CharSequence>(
MySpinnerListenerDemo.this, android.R.layout.simple_spinner_item,
MySpinnerListenerDemo.this.areaData[position]); //定义所有的列表项
MySpinnerListenerDemo.this.adapterArea.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item); // 设置显示风格,好看些(推荐)
MySpinnerListenerDemo.this.area.setAdapter
(MySpinnerListenerDemo.this.adapterArea); //设置二级下拉列表选项内容
}
public void onNothingSelected(AdapterView<?> arg0) { //表示没有选项的时候触发
}
}
}