Android省市県三級連動(android-wheelの使用)

9657 ワード

転載は出典を明記してください.http://blog.csdn.net/lmj623565791/article/details/23382805
今日はグループの中で冗談を言っていましたが、Android Wheelというコントロールは、Andriodに内蔵されているコントロールだと思っていました.googleは、githubのコントロールであることを発見しました.
ダウンロード先:https://code.google.com/p/android-wheel/省市県の3級連動に適していることを発見して1つ作った.
まず効果図を見てみましょう.
Android 省市县 三级联动(android-wheel的使用)_第1张图片
1.まずgithub上のwheelプロジェクトAndroid 省市县 三级联动(android-wheel的使用)_第2张图片を導入する
2、プロジェクトを新規作成し、右クリック->Properties->Androidでwheelをlibに追加することを選択します.
Android 省市县 三级联动(android-wheel的使用)_第3张图片
上記の2つのステップは、すべてのオープンソースプロジェクトをインポートするプロセスです.
3、次はコードの作成を開始する:まず省市区のjsonファイルで、assertsのcityに置く.json:
大体のフォーマットは先に理解して、後でコードはこのようなフォーマットによって解析します
{"citylist":
	[{"p":"  ",
	  "c":[{"n":"   ",
	  "a":[{"s":"   "},{"s":"   "},{"s":"   "}]
	}]
}

4、レイアウトファイル、比較的簡単に3つのWheelViewはそれぞれ省、市、県を代表して、もう一つのボタンがあります.
<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:background="#000000"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="     "
        android:textColor="#ffffff"
        android:textSize="20sp" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/layout_bg"
        android:orientation="horizontal" >

        <kankan.wheel.widget.WheelView
            android:id="@+id/id_province"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" >
        </kankan.wheel.widget.WheelView>

        <kankan.wheel.widget.WheelView
            android:id="@+id/id_city"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" >
        </kankan.wheel.widget.WheelView>

        <kankan.wheel.widget.WheelView
            android:id="@+id/id_area"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" >
        </kankan.wheel.widget.WheelView>
    </LinearLayout>
    
    <Button 
		android:onClick="showChoose"
		android:layout_gravity="right"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="  "
        />
    

</LinearLayout>
5、Activityの作成:注釈はかなり詳細で、節は省略します.
package com.example.wheel_province;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

/**
 * 
 * @author zhy
 * 
 */
public class CitiesActivity extends Activity implements OnWheelChangedListener
{
	/**
	 *            json     ,        null
	 */
	private JSONObject mJsonObj;
	/**
	 *   WheelView  
	 */
	private WheelView mProvince;
	/**
	 *   WheelView  
	 */
	private WheelView mCity;
	/**
	 *   WheelView  
	 */
	private WheelView mArea;

	/**
	 *    
	 */
	private String[] mProvinceDatas;
	/**
	 * key -   value -  s
	 */
	private Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
	/**
	 * key -   values -  s
	 */
	private Map<String, String[]> mAreaDatasMap = new HashMap<String, String[]>();

	/**
	 *       
	 */
	private String mCurrentProviceName;
	/**
	 *       
	 */
	private String mCurrentCityName;
	/**
	 *       
	 */
	private String mCurrentAreaName ="";

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.citys);

		initJsonData();

		mProvince = (WheelView) findViewById(R.id.id_province);
		mCity = (WheelView) findViewById(R.id.id_city);
		mArea = (WheelView) findViewById(R.id.id_area);

		initDatas();

		mProvince.setViewAdapter(new ArrayWheelAdapter<String>(this, mProvinceDatas));
		//   change  
		mProvince.addChangingListener(this);
		//   change  
		mCity.addChangingListener(this);
		//   change  
		mArea.addChangingListener(this);

		mProvince.setVisibleItems(5);
		mCity.setVisibleItems(5);
		mArea.setVisibleItems(5);
		updateCities();
		updateAreas();

	}

	/**
	 *       ,   WheelView   
	 */
	private void updateAreas()
	{
		int pCurrent = mCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mAreaDatasMap.get(mCurrentCityName);

		if (areas == null)
		{
			areas = new String[] { "" };
		}
		mArea.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
		mArea.setCurrentItem(0);
	}

	/**
	 *       ,   WheelView   
	 */
	private void updateCities()
	{
		int pCurrent = mProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null)
		{
			cities = new String[] { "" };
		}
		mCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
		mCity.setCurrentItem(0);
		updateAreas();
	}

	/**
	 *     Json  ,     Json     
	 */
	private void initDatas()
	{
		try
		{
			JSONArray jsonArray = mJsonObj.getJSONArray("citylist");
			mProvinceDatas = new String[jsonArray.length()];
			for (int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject jsonP = jsonArray.getJSONObject(i);//     json  
				String province = jsonP.getString("p");//    

				mProvinceDatas[i] = province;

				JSONArray jsonCs = null;
				try
				{
					/**
					 * Throws JSONException if the mapping doesn't exist or is
					 * not a JSONArray.
					 */
					jsonCs = jsonP.getJSONArray("c");
				} catch (Exception e1)
				{
					continue;
				}
				String[] mCitiesDatas = new String[jsonCs.length()];
				for (int j = 0; j < jsonCs.length(); j++)
				{
					JSONObject jsonCity = jsonCs.getJSONObject(j);
					String city = jsonCity.getString("n");//    
					mCitiesDatas[j] = city;
					JSONArray jsonAreas = null;
					try
					{
						/**
						 * Throws JSONException if the mapping doesn't exist or
						 * is not a JSONArray.
						 */
						jsonAreas = jsonCity.getJSONArray("a");
					} catch (Exception e)
					{
						continue;
					}

					String[] mAreasDatas = new String[jsonAreas.length()];//        
					for (int k = 0; k < jsonAreas.length(); k++)
					{
						String area = jsonAreas.getJSONObject(k).getString("s");//      
						mAreasDatas[k] = area;
					}
					mAreaDatasMap.put(city, mAreasDatas);
				}

				mCitisDatasMap.put(province, mCitiesDatas);
			}

		} catch (JSONException e)
		{
			e.printStackTrace();
		}
		mJsonObj = null;
	}

	/**
	 *  assert          json  ,     json  
	 */
	private void initJsonData()
	{
		try
		{
			StringBuffer sb = new StringBuffer();
			InputStream is = getAssets().open("city.json");
			int len = -1;
			byte[] buf = new byte[1024];
			while ((len = is.read(buf)) != -1)
			{
				sb.append(new String(buf, 0, len, "gbk"));
			}
			is.close();
			mJsonObj = new JSONObject(sb.toString());
		} catch (IOException e)
		{
			e.printStackTrace();
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * change     
	 */
	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue)
	{
		if (wheel == mProvince)
		{
			updateCities();
		} else if (wheel == mCity)
		{
			updateAreas();
		} else if (wheel == mArea)
		{
			mCurrentAreaName = mAreaDatasMap.get(mCurrentCityName)[newValue];
		}
	}

	public void showChoose(View view)
	{
		Toast.makeText(this, mCurrentProviceName + mCurrentCityName + mCurrentAreaName, 1).show();
	}
}

これでコードの作成が完了しました.もしこの文章があなたに役に立つなら、一番いいです~へへ~
ここをクリック