转载请注明出处: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>
- 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