在开发中我们经常要遇到类似Spinner级联菜单的效果,下面就是Spinner级联菜单效果的实现
activity_main.xml
1 26 7 51 5211 12 13 14 15 16 17 18 32 3324 25 26 31 37 38 43 44 50
array.xml
1 23 4 9 10- 请选择:
5- 北京
6- 上海
7- 武汉
8
strings.xml
12 3 SpinnerJi 4Hello world! 5Settings 6MainActivity 7下拉列表框选项 8选择你喜欢的城市 9选择你喜欢的城区 10 11
activity
1 package com.example.spinnerji; 2 import android.app.Activity; 3 import android.os.Bundle; 4 import android.view.View; 5 import android.widget.AdapterView; 6 import android.widget.AdapterView.OnItemSelectedListener; 7 import android.widget.ArrayAdapter; 8 import android.widget.Spinner; 9 import android.widget.TextView;10 11 public class MainActivity extends Activity {12 private Spinner city;// 一级菜单13 private Spinner area;// 二级菜单14 private TextView cityTextView;15 private TextView areTextView;16 private String[][] areaData = new String[][] {17 {"请选择:"},18 {"朝阳区","海淀区","西城区","大兴区","怀柔区"},19 {"闵行区"},20 {"洪山区","武昌区","东西湖区"}};21 private ArrayAdapteradapterArea;22 23 @Override24 public void onCreate(Bundle savedInstanceState) {25 super.onCreate(savedInstanceState);26 setContentView(R.layout.activity_main);27 cityTextView=(TextView) findViewById(R.id.tex_city);28 areTextView=(TextView) findViewById(R.id.tex_area);29 city = (Spinner) findViewById(R.id.city);// 取得下拉列表框30 // 由于一个城市有多个市区,为了简单起见下面我们定义一个数组,通过数组保存若干个城市,而实际中需要单独的数据31 area = (Spinner) findViewById(R.id.area);// 取得下拉列表框32 city.setOnItemSelectedListener(new OnItemSelectedListenerImpl());33 area.setOnItemSelectedListener(new OnItemSelectedListenerImpl());34 city.setPrompt("选择你喜欢的城市");35 city.setPrompt("选择你喜欢的城区");36 }37 38 private class OnItemSelectedListenerImpl implements OnItemSelectedListener {39 public void onItemSelected(AdapterView parent, View view,40 int position, long id) { // 选项改变的时候触发41 42 switch (parent.getId()) {43 case R.id.city:44 String value = (String) parent.getItemAtPosition(position);// 得到选中的选项45 cityTextView.setText(value);46 adapterArea = new ArrayAdapter (MainActivity.this,android.R.layout.simple_expandable_list_item_1,// 显示风格47 areaData[position]);// 在列表视图中所代表的对象。48 area.setAdapter(adapterArea);// 把adapterArea添加到area49 break;50 51 case R.id.area:52 String value2 = (String) parent.getItemAtPosition(position);// 得到选中的选项53 areTextView.setText(value2);54 break;55 }56 57 }58 59 public void onNothingSelected(AdapterView arg0) { // 没有选项的时候触发60 // 一般不关心61 62 }63 64 }65 }