Spinner控件下拉框运用在地址的二级联动中
效果如图:
XML关键代码:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="match_parent"
- android:layout_height="match_parent">
- <Spinner
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/s_main_province"></Spinner>
- <Spinner
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/s_main_city"></Spinner>
- </LinearLayout>
Java关键代码:
- public class MainActivity extends AppCompatActivity {
- private Spinner s_main_province;
- private Spinner s_main_city;
- private List<String> province;
- int index=0;
- private SimpleAdapter sadapter;
- private ArrayAdapter cityAdapter;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- s_main_province = (Spinner) findViewById(R.id.s_main_province);
- s_main_city = (Spinner) findViewById(R.id.s_main_city);
- //设置省份下拉列表的适配器
- province=new ArrayList<>();
- province.add("湖南省") ;
- province.add("湖北省");
- province.add("甘肃省");
- //设置图片集合
- List<Integer> images=new ArrayList<>();
- images.add(R.drawable.bird);
- images.add(R.drawable.cat);
- images.add(R.drawable.cow);
- List<Map<String,Object>> lists=new ArrayList<>();
- for (int i = 0; i < province.size(); i++) {
- Map<String,Object> map=new HashMap<>();
- map.put("province",province.get(i));
- map.put("images",images.get(i));
- lists.add(map);
- }
- //设置市的集合
- String city1[]={"长沙市","湘潭市","衡阳市"};
- String city2[]={"武汉市","黄石市","襄阳市"};
- String city3[]={"兰州","白银市","平凉市"};
- final String str[][]={city1,city2,city3};
- //省域市集合
- final Map<String ,String[]> cityLists=new ArrayMap<>();
- for (int i = 0; i <province.size() ; i++) {
- cityLists.put(province.get(i),str[i]);
- }
- sadapter = new SimpleAdapter(this,lists,android.R.layout.activity_list_item,new String[]{"province","images"},new int[]{android.R.id.text1,android.R.id.icon});
- //给下拉列表设置适配器
- s_main_province.setAdapter(sadapter);
- s_main_province.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
- //给市的下拉框设置配置器
- index=position;
- cityAdapter=new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,cityLists.get(province.get(index)));
- s_main_city.setAdapter(cityAdapter);
- }
- @Override
- public void onNothingSelected(AdapterView<?> parent) {
- }
- });
- }
- }