在Android的开发中,经常需要添加地址,这里是一个简单的根据xml文件来解析去获取省市地址的联动
先在res目录下新建一个文件夹xml,把xml文件放在这个文件夹下,xml的格式是这样的,详细文件在下载demo里
<p p_id = "01"> <pn>北京</pn> <c c_id="0101"><cn>北京</cn> <d d_id="101010100">北京</d> <d d_id="101010200">海淀</d> <d d_id="101010300">朝阳</d> <d d_id="101010400">顺义</d> <d d_id="101010500">怀柔</d> <d d_id="101010600">通州</d> <d d_id="101010700">昌平</d> <d d_id="101010800">延庆</d> <d d_id="101010900">丰台</d> <d d_id="101011000">石景山</d> <d d_id="101011100">大兴</d> <d d_id="101011200">房山</d> <d d_id="101011300">密云</d> <d d_id="101011400">门头沟</d> <d d_id="101011500">平谷</d> </c> </p>
public void getXmlData(){ //获取xml文件中的资源 XmlResourceParser parser = getResources().getXml(R.xml.citys_weather); int type; try { type = parser.getEventType(); List<String> citys = null; //判断是否到文件结束 while(type != XmlPullParser.END_DOCUMENT){ //判断是否是文件的开始 if(type == XmlPullParser.START_DOCUMENT){ data1 = new ArrayList<String>(); data2 = new ArrayList<List<String>>(); //判断是否是文件的开始标签 }else if(type == XmlPullParser.START_TAG){ String name = parser.getName(); if("pn".equals(name)){ data1.add(parser.nextText()); citys = new ArrayList<String>(); }else if("d".equals(name)){ citys.add(parser.nextText()); } //判断是否是文件的结束标签 }else if(type == XmlPullParser.END_TAG){ String name = parser.getName(); if("p".equals(name)){ data2.add(citys); } } type = parser.next(); } } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, data1); spinner1.setAdapter(adapter1); spinner1.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, data2.get(position)); spinner2.setAdapter(adapter2); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } });
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/xiaoxiaomao123098/article/details/47722751