样式部分xml
110 11 16 17 23 24 30 31
arrays部分xml
1 23 4 8- -省份-
5- 北京市
6- 河北省
79 16- -城市-
10- 承德市
11- 石家庄
12- 邯郸市
13- 邢台市
14- 廊坊市
1517 23- -城市-
18- 海淀区
19- 朝阳区
20- 崇文区
21- 昌平区
22
Activity 部分
1 package com.example.android_spinner; 2 3 import android.os.Bundle; 4 import android.app.Activity; 5 import android.view.Menu; 6 import android.view.View; 7 import android.widget.AdapterView; 8 import android.widget.ArrayAdapter; 9 import android.widget.Spinner;10 11 public class MainActivity extends Activity {12 // 声明组件13 private Spinner sr1;14 private Spinner sr2;15 16 @Override17 protected void onCreate(Bundle savedInstanceState) {18 super.onCreate(savedInstanceState);19 setContentView(R.layout.activity_main);20 // 获取组件21 sr1 = (Spinner) this.findViewById(R.id.spinner1);22 sr2 = (Spinner) this.findViewById(R.id.spinner2);23 // 添加String数组24 String[] province = getResources().getStringArray(R.array.province);25 ;26 // 将数组配置器链接上预置的文件27 // ArrayAdapteraa = new ArrayAdapter (this,28 // android.R.layout.simple_spinner_item,province);29 30 // 这样就可以直接获取xml中的数组了31 ArrayAdapter aa = ArrayAdapter.createFromResource(this,32 R.array.province, android.R.layout.simple_spinner_item);33 34 // 设置下拉菜单的样式35 aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);36 // 将数据绑定到spinner上37 sr1.setAdapter(aa);38 39 // 添加监听事件40 41 sr1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {42 43 @Override44 public void onItemSelected(AdapterView arg0, View arg1,45 int arg2, long arg3) {46 // 得到事件中选中的值47 Spinner s = (Spinner) arg0;48 String pro = (String) s.getItemAtPosition(arg2);49 ArrayAdapter cityAdapter = null;50 // 获取所在省含有哪些市(从资源数组文件中获取数据)51 if (pro.equals("河北省")) {52 53 cityAdapter = ArrayAdapter.createFromResource(54 MainActivity.this, R.array.hb,55 android.R.layout.simple_spinner_item);56 } else if (pro.equals("北京市")) {57 58 cityAdapter = ArrayAdapter.createFromResource(59 MainActivity.this, R.array.bj,60 android.R.layout.simple_spinner_item);61 } 62 sr2.setAdapter(cityAdapter);63 }64 65 @Override66 public void onNothingSelected(AdapterView arg0) {67 // TODO Auto-generated method stub68 69 }70 71 });72 73 }74 75 @Override76 public boolean onCreateOptionsMenu(Menu menu) {77 // Inflate the menu; this adds items to the action bar if it is present.78 getMenuInflater().inflate(R.menu.main, menu);79 return true;80 }81 82 }
实现效果: