1.数据结构
ProvinceModel(String name, List<CityModel> cityList)
CityModel(String name, List<DistrictModel> districtList)
DistrictModel(String name, String zipcode)
并实现getset方法
2.要解析的xml文件province_data.xml
<root>
<province name="安徽省">
<city name="安庆市">
<district name="枞阳县" zipcode="246000" />
<district name="大观区" zipcode="246000" />
....
</city>
.......
</province>
<province name="四川省">
.......
3.xml解析过程
protected void initProvinceDatas(){
AssetManager asset = getAssets();
try {
InputStream input = asset.open("province_data.xml");
// 创建一个解析xml的工厂对象
SAXParserFactory spf = SAXParserFactory.newInstance();
// 解析xml
SAXParser parser = spf.newSAXParser();
XmlParserHandler handler =new XmlParserHandler();
parser.parse(input, handler);
input.close();
// 获取解析出来的数据
mProvinces = handler.getDataList();
}catch (Throwable e) {
e.printStackTrace();
}finally {
}
}
4. 添加数据
public void oldIterator() {
if(mProvinces !=null){
for (ProvinceModel p :mProvinces){
List cities = p.getCityList();
ArrayList cityStrs =new ArrayList<>(cities.size());//城市List
ArrayList> dts =new ArrayList<>();// 地区List
for (CityModel c :cities){
cityStrs.add(c.getName());// 把城市名称放入cityStrs
List districts = c.getDistrictList();
ArrayList districtStrs =new ArrayList<>(districts.size());
for (DistrictModel d : districts) {
districtStrs.add(d.getName());// 把地区名称放入districtStrs }
dts.add(districtStrs);}
mCities.add(cityStrs);// 组装城市数据
mDistricts.add(dts);//组装地区数据
}}}
5.弹出实现
private OptionsPickerView pvOptions;
..............
pvOptions =new OptionsPickerBuilder(AddressAddActivity.this,new OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1,int options2,int options3 ,View v) {
//返回的分别是三个级别的选中位置
String addresss =mProvinces.get(options1).getName() +" "
+mCities.get(options1).get(options2)+" "
+mDistricts.get(options1).get(options2).get(options3);
mTxtAddress.setText(addresss);
}
})
.setTitleText("选择城市")
.setCyclic(false,false,false)
.setCancelText("Cancel")//取消按钮文字
.setSubmitText("Sure")//确认按钮文字
.setContentTextSize(18)//滚轮文字大小
.setTitleSize(20)//标题文字大小
.setLabels("省","市","区")//设置选择的三级单位
.build();
pvOptions.setPicker((ArrayList)mProvinces,mCities,mDistricts);
pvOptions.show();
如果弹出PickerView时还会弹出虚拟键盘,可以设置.setDecorView((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content))
6.测试效果
参考资料:
2.菜鸟商城-菜鸟窝