【Android组件之Spinner高级功能--级联选择】
一、省市区级联操作
Web系统的select下拉列表,可以实现省市区级联操作,选择省出现该省下面的城市,而不是其他省的城市,如下图:
那么Android系统中的下拉列表组件Spinner能否实现省市区级联呢,答案是肯定的,如下图:
二、Android省市区级联源码如下:
1)界面文件,参考
永久链接: http://gaojingsong.iteye.com/blog/2356364
预览文章: 【Android组件之Spinner使用】
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="城市:" />
<Spinner android:id="@+id/sp" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:entries="@array/my_citys"
android:prompt="@string/info" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="区域:" />
<Spinner android:id="@+id/areas" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:entries="@array/my_areas"
android:prompt="@string/info" />
2)级联JAVA代码如下:
//定义二级列表数组
private String[][] areas = new String[][]{{"海淀","朝阳"},{"浦东"},{"广州","东莞","深圳"}};
Spinner areasSpinner = (Spinner) this.findViewById(R.id.areas);
Spinner spCity = (Spinner) this.findViewById(R.id.sp);
//注册监听事件
spCity.setOnItemSelectedListener(new MyCityItemSelectedListener());
监听核心代码
private class MyCityItemSelectedListener implements OnItemSelectedListener{
/**
parent The AdapterView where the selection happened
view The view within the AdapterView that was clicked
position The position of the view in the adapter
id The row id of the item that is selected
*/
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayAdapter adapter = new ArrayAdapter<String>(HelloActivity.this,
android.R.layout.simple_spinner_item, HelloActivity.this.areas[position]);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
areasSpinner.setAdapter(adapter);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}