Android 省市縣 三級聯動(android-wheel的使用)

jopen 8年前發布 | 18K 次閱讀 Java開發

轉載請注明出處:http://blog.csdn.net/lmj623565791/article/details/23382805

今天沒事跟群里面侃大山,有個哥們說道Android Wheel這個控件,以為是Andriod內置的控件,google一把,發現是個github上的一個控件。

下載地址:https://code.google.com/p/android-wheel/    發現很適合做省市縣三級聯動就做了一個。

先看下效果圖:

1、首先導入github上的wheel項目

2、新建個項目,然后選擇記得右鍵->Properties->Android中將wheel添加為lib:


上面兩個步驟是導入所有開源項目的過程了。

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();
    }
}

這樣就完成了代碼的編寫,如果這篇文章對你有幫助,可以頂一個~嘿嘿~


源碼下載點擊這里



來自: http://blog.csdn.net//lmj623565791/article/details/23382805

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!