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<String> 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) {

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值