首先来张效果图:
PickerView的加载路径:
compile 'com.bigkoo:pickerview:2.0.8'
数据加载和解析:
private ArrayList<ProvinceBean> options1Items = new ArrayList<ProvinceBean>(); private ArrayList<ArrayList<String>> options2Items = new ArrayList<ArrayList<String>>(); private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<ArrayList<ArrayList<String>>>();
public static void getAllAreaPlace(ArrayList<ProvinceBean> options1Items, ArrayList<ArrayList<String>> options2Items, ArrayList<ArrayList<ArrayList<String>>> options3Items) { AllAreaBean allAreaBean = JSON.parseObject(AllCityUtils.getAllCity(), AllAreaBean.class); //获取所有的省份名字 for (int i = 0; i < allAreaBean.getProvince().size(); i++) { ProvinceBean provinceBean = new ProvinceBean(); provinceBean.setId(i); provinceBean.setName(allAreaBean.getProvince().get(i).getName()); options1Items.add(provinceBean); //存放地区 ArrayList<ArrayList<String>> listArea = new ArrayList<>(); //存放城市名字 ArrayList<String> listCity = new ArrayList<>(); for (int j = 0; j < allAreaBean.getProvince().get(i).getCity().size(); j++) { if (allAreaBean.getProvince().get(i).getCity().size() == 1) { listCity.add(""); } else { listCity.add(allAreaBean.getProvince().get(i).getCity().get(j).getName()); } listArea.add((ArrayList<String>) allAreaBean.getProvince().get(i).getCity().get(j).getArea()); } options3Items.add(listArea); options2Items.add(listCity); } }
//PickerView选择器 OptionsPickerView pvOptions;
pvOptions = new OptionsPickerView(this);
/** * 添加城市信息 */ private void addCityMessage() { AreaUtils.getAllAreaPlace(options1Items,options2Items,options3Items); //三级联动效果 pvOptions.setPicker(options1Items, options2Items, options3Items, true); //设置标题 pvOptions.setTitle("选择城市"); //设置监听 // pvOptions.setSelectOptions(1, 1, 1); pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() { @Override public void onOptionsSelect(int i, int i1, int i2) { //返回的分别是三个级别的选中位置 address = options1Items.get(i).getPickerViewText() + "省 " + options2Items.get(i).get(i1) + "市 " + options3Items.get(i).get(i1).get(i2) + "区"; etAddress1.setText(address); } }); }
case R.id.et_message_address1: pvOptions.show(); break;