Android开发之解析XML并实现三级联动效果

请尊重他人的劳动成果,转载请注明出处:Android开发之解析XML并实现三级联动效果

       本实例主要应用XmlPullParser解析XML文档中的省市区,然后将数据绑定到Spinner上实现三级联动的效果。关于XmlPullParser的详解大家可以参考《Android开发之使用PULL解析和生成XML》一文。

运行效果图:


程序代码:

核心代码:

<pre name="code" class="java">package com.jph.sevice;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import android.os.Handler;
import android.os.Message;
import android.util.Xml;

/**
 * 解析省、市、区xml
 * @author jph
 * Date:2014.09.25
 */
public class PullProvince {	
	public static final int PARSESUCCWSS=0x2001;
	private Handler handler;
	public PullProvince(Handler handler) {
		// TODO Auto-generated constructor stub
		this.handler=handler;
	}
	/**
	 * 获取所有省份城市以及区	
	 * @author jph
	 * Date:2014.09.25	
	 */
	public void getProvinces(final InputStream inStream) {			
		new Thread(new Runnable() {			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					XmlPullParser pullParser = Xml.newPullParser();
					pullParser.setInput(inStream, "UTF-8");
					int event;
						event = pullParser.getEventType();
					Map<String, Map<String, List<String>>> provinces = new HashMap<String, 
							Map<String, List<String>>>();// 省份
					Map<String, List<String>> cities=null;// 城市		
					ArrayList<String> areaAll = null;
					String pName = "";// 省份名称
					String cName = "";// 城市名称
					String aName = "";// 地区名
					String targetName = "";// 当前节点的名称
					while (event != XmlPullParser.END_DOCUMENT) {
						targetName = pullParser.getName();
						switch (event) {
						case XmlPullParser.START_TAG:
							if ("province".equals(targetName)) {// 处理省份节点				
								pName = pullParser.getAttributeValue(0);// 当前省份名
								cities=new HashMap<String, List<String>>();
							} else if ("city".equals(targetName)) {// 处理城市节点				
								cName = pullParser.getAttributeValue(0);
								areaAll = new ArrayList<String>();// 地区
							} else if ("area".equals(targetName)) {// 处理地区节点
								aName = pullParser.getAttributeValue(0);
							}
							break;
						case XmlPullParser.END_TAG:
							if (targetName.equals("area")) {
								areaAll.add(aName);
							} else if (targetName.equals("city")) {
								cities.put(cName, areaAll);
							} else if (targetName.equals("province")) {
								provinces.put(pName, cities);
							}
							break;
						}
						event = pullParser.next();
					}
					Message message=new Message();					
					message.obj=provinces;//将解析出的数据放到message中传给主线程
					message.what=PARSESUCCWSS;
					handler.sendMessage(message);//通知主线程数据解析完毕
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}		
			}
		}).start();		
	}
}


Activity:

<pre name="code" class="java">package com.jph.px;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import com.jph.sevice.PullProvince;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
/**
 * 省,市,区三级联动
 * @author jph
 * Date:2014.09.25
 */
public class MainActivity extends Activity {
	private Spinner province,city,area;	
	private Map<String, Map<String, List<String>>> data=null;
	/**当前的选择的省份**/
	private	String currentProvince;
	/**当前的选择的城市**/
	private	String currentCity;
	private PullProvince pullProvince;	
//	/**当前的选择的区**/
//	private	String currentArea;
	private Handler mHandler=new Handler(){
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case PullProvince.PARSESUCCWSS://数据解析完毕,加载数据
				data=(Map<String, Map<String, List<String>>>) msg.obj;
				initData();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		province=(Spinner)findViewById(R.id.province);
		city=(Spinner)findViewById(R.id.city);
		area=(Spinner)findViewById(R.id.area);	
		pullProvince=new PullProvince(mHandler);
		InputStream inStream = this.getClass().getClassLoader().
				getResourceAsStream("province_city.xml");		
	    pullProvince.getProvinces(inStream);			
	}	
	/**
	 * 初始化数据
	 */
	private void initData(){		
		if (data!=null) {
			String[]arrStrings= data.keySet().toArray(new String[0]);
			System.out.println(arrStrings);			
			//将省份信息填充到 province Spinner
			province.setAdapter(new ArrayAdapter<String>(this, 
					android.R.layout.simple_list_item_multiple_choice,arrStrings));
			currentProvince=getCurrentProvince();	
			bindCityAdapter(currentProvince);
			currentCity=getCurrentCity();			
			bindAreaAdapter(currentCity);			
			setOnItemSelectedListener();			
		}
	}
	private void bindAreaAdapter(String currentCity) {
		// TODO Auto-generated method stub
		//根据当前显示的城市将对应的区填充到area Spinner		
		area.setAdapter(new ArrayAdapter<String>(this, 
				android.R.layout.simple_list_item_multiple_choice,
				data.get(currentProvince).get(currentCity)));
	}
	private void bindCityAdapter(String currentProvince) {
		// TODO Auto-generated method stub
		//根据当前显示的省份将对应的城市填充到city Spinner
		city.setAdapter(new ArrayAdapter<String>(this, 
				android.R.layout.simple_list_item_multiple_choice,data.
				get(currentProvince).keySet().toArray(new String[0])));
	}
	/**
	 * 为Spinner设置监听器
	 */
	private void setOnItemSelectedListener() {
		// TODO Auto-generated method stub
		province.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				currentProvince=getCurrentProvince();
				bindCityAdapter(currentProvince);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		city.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				currentCity=getCurrentCity();
				bindAreaAdapter(currentCity);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		area.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this,area.getSelectedItem().toString(), 
						Toast.LENGTH_SHORT).show();	
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});	
	}

	/**获取当前选择的省份
	 * @return String:当前选择的省份
	 */
	private String getCurrentProvince() {
		// TODO Auto-generated method stub
		return province.getSelectedItem().toString();
	}
	/**获取当前选择的城市
	 * @return String:当前选择的城市
	 */
	private String getCurrentCity() {
		// TODO Auto-generated method stub
		return city.getSelectedItem().toString();
	}
}


布局文件:

<pre name="code" class="html"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
	<Spinner android:id="@+id/province"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    />
	<Spinner android:id="@+id/city"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"/>
	<Spinner android:id="@+id/area"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"/>
	<TextView android:id="@+id/tv"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"/>
</LinearLayout>







郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。