android 二级联动,省份和城市


实现思路:
二级联动
1、获取两个id

2、设置数据 
(1)list 一个
   String[] 3个

3、适配器两个

4、给第一个下拉框添加点击事件
    实例化并给第二个适配器设值










public class SpinnerAtivity extends AppCompatActivity{

    private Spinner spinner2;
    private Spinner spinner1;
    private List> list;
    private String[] province;
    private String[] city0;
    private String[] city1;
    private String[] city2;
    private int[] images;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spniner);
        //获取值
        spinner1 = (Spinner) findViewById(R.id.s_item_spniner1);
        spinner2 = (Spinner) findViewById(R.id.s_item_spniner2);
        //获取数据
        images = new int[]{R.drawable.cow,R.drawable.chicken,R.drawable.cat};
        province = new String[]{"湖南省","湖北省","海南省"};
        city0 = new String[]{"郴州市","衡阳市","益阳市"};
        city1 = new String[]{"武汉市","荆州市","黄冈市"};
        city2 = new String[]{"海口市","三亚市","文昌市"};
        list = new ArrayList<>();
        for (int i = 0; i < province.length; i++) {
            Map map=new HashMap<>();
            map.put("titles",province[i]);
            map.put("images",images[i]);
            map.put(province[0],city0[i]);
            map.put(province[1],city1[i]);
            map.put(province[2],city2[i]);
            list.add(map);
        }
        //实例化适配器
        SimpleAdapter simpleAdapter=new SimpleAdapter(this,list,android.R.layout.activity_list_item,new String[]{"titles","images"},new int[]{android.R.id.text1,android.R.id.icon});
      //  SimpleAdapter simpleAdapter2=new SimpleAdapter(this,list,android.R.layout.activity_list_item,new String[]{"images",province[0]},new int[]{android.R.id.icon,android.R.id.text1});
        spinner1.setAdapter(simpleAdapter);
      //  spinner2.setAdapter(simpleAdapter2);

        //给下拉框设置点击事件
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView adapterView, View view, int i, long l) {
                SimpleAdapter simpleAdapter2=new SimpleAdapter(SpinnerAtivity.this,list,android.R.layout.activity_list_item,new String[]{"images",province[i]},new int[]{android.R.id.icon,android.R.id.text1});
                spinner2.setAdapter(simpleAdapter2);
            }

            @Override
            public void onNothingSelected(AdapterView adapterView) {

            }
        });
    }
}

 
  android 二级联动,省份和城市_第1张图片 
  

android 二级联动,省份和城市_第2张图片


你可能感兴趣的:(android 二级联动,省份和城市)