Android三级联动示例

package com.zyx.another.spinner;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    private Spinner province,city,district;
    private ArrayAdapter provinceAdpter,cityAdapter,districtAdapter;
    private String[] provinceArray;
    private String[][] cityArray;
    private String[][][] districtArray;
    private static int provincePosition = 0;  //记录选中的省份标记

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addressInit(); //初始化地址数据

        province = (Spinner)findViewById(R.id.province);
        city = (Spinner)findViewById(R.id.city);
        district = (Spinner)findViewById(R.id.district);


        //初始化下拉列表 0表示默认第一个选项
        provinceAdpter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,provinceArray);
        cityAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,cityArray[0]);
        districtAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,districtArray[0][0]);

        province.setAdapter(provinceAdpter);
        city.setAdapter(cityAdapter);
        district.setAdapter(districtAdapter);

        //监听Spinner事件
        province.setOnItemSelectedListener(this);
        city.setOnItemSelectedListener(this);
        district.setOnItemSelectedListener(this);

    }

    public void addressInit() {
        provinceArray = new String[] {"湖南","广东"};
        cityArray = new String[][] {{"长沙","株洲"},{"广州","珠海"}};
        districtArray = new String[][][] {{{"岳麓区","天心区","开福区"},{"天元区","荷塘区","芦淞区"}},{{"越秀区","天河区","白云区"},{"香洲区","斗门区","金湾区"}}};
    }

    @Override
    public void onItemSelected(AdapterView adapterView, View view, int i, long l) {

     switch (adapterView.getId()){
         case R.id.province:
             cityAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,cityArray[i]);
             city.setAdapter(cityAdapter);
             provincePosition= i;
             break;

         case R.id.city:
             districtAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,districtArray[provincePosition][i]);
             district.setAdapter(districtAdapter);
             break;

         case R.id.district:

             break;
     }

    }

    @Override
    public void onNothingSelected(AdapterView adapterView) {

    }
}

你可能感兴趣的:(Android三级联动示例)