地址选择器,效果图如下
实现思路
(1)OkHttp发起请求,从html文件获取地址JSON数据
(2)利用三个NumberPicker实现选择
实现代码
- okHttp 发起Get请求, 并且解析JSON数据(利用GSON解析),这里值得注意的是,OkHttp中返回的response.boby.string的有效性只有一次,一旦被调用,就不能再次调用了,取出来是空值(“”)
public class ResourceManager {
List<ProvinceModel> list = new ArrayList<ProvinceModel>();
Callable callable;
public ResourceManager(Callable callable){
this.callable = callable;
getData();
}
public void getData(){
//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
//创建一个Request
final Request request = new Request.Builder()
.url("http://192.168.0.151:80/1.html")
.build();
//new call
Call call = mOkHttpClient.newCall(request);
//请求加入调度
call.enqueue(new Callback()
{
@Override
public void onFailure(Call call, IOException e) {
Log.d("wnw", "failure");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//Log.d("wnw", "success" + response.body().string());
parseData(response.body().string()); //response.body().string()调用一次就被清除了,首次有效
}
});
}
private void parseData(String data){
try {
if (data.isEmpty()){
return;
}
JSONObject object = new JSONObject(data);
JSONArray jsonArray = object.getJSONArray("data");
list = formJsonToArray(jsonArray.toString(), new TypeToken<List<ProvinceModel>>() {
}.getType());
callable.onCall(list);
}catch (Exception e){
e.printStackTrace();
}
}
public static <T> T formJsonToArray(String json, Type t) {
if (json == null) {
return null;
}
return new Gson().fromJson(json, t);
}
interface Callable{
void onCall(List<ProvinceModel> list);
}
}
- 创建Dialog, 并且将三级联动的数据加载到Dialog中
public class PickLocateDialog {
private static String TAG = "PickLocateDialog";
Activity mContext;
NumberPicker mProvicePicker;
NumberPicker mCityPicker;
NumberPicker mDistrictPicker;
List<ProvinceModel> mProvinceList;
private AlertDialog ad;
/**
* 所有省集合
*/
protected String[] mProvinceDatas;
/**
* 所有市的集合
* key - 省 value - 市
*/
protected Map<String, Object> mCitisDatasMap = new HashMap<>();
protected Map<String, Object> mDistrictMap = new HashMap<>();
// protected List<Map<String, Object>> cityList = new ArrayList<>();
/**
* 当前省的名称
*/
protected String mCurrentProviceName;
/**
* 当前市的名称
*/
protected String mCurrentCityName;
AddressPickedListener mListener;
public PickLocateDialog(Activity mContext, AddressPickedListener listener) {
this.mContext = mContext;
this.mListener = listener;
initProvinceDatas();
}
public AlertDialog locatePickDialog() {
FrameLayout locatePickLayout = (FrameLayout) mContext.getLayoutInflater().inflate(R.layout.dialog_pick_locate, null);
mProvicePicker = (NumberPicker) locatePickLayout.findViewById(R.id.monthpicker);
mCityPicker = (NumberPicker) locatePickLayout.findViewById(R.id.hourpicker);
mDistrictPicker = (NumberPicker) locatePickLayout.findViewById(R.id.minuteicker);
init();
ad = new AlertDialog.Builder(mContext).setView(locatePickLayout).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ProvinceModel provinceModel = mProvinceList.get(mProvicePicker.getValue());
CityModel cityModel = provinceModel.getChild().get(mCityPicker.getValue());
DistrictModel districtModel = null;
if (cityModel.getChild() != null) {
districtModel = cityModel.getChild().get(mDistrictPicker.getValue());
}
mListener.onAddressPicked(provinceModel, cityModel, districtModel);
// String province = mProvinceDatas[mProvicePicker.getValue()];
// String city = ((String[]) mCitisDatasMap.get(mProvinceDatas[mProvicePicker.getValue()]))[mCityPicker.getValue()];
// locate.setText(province + "-"
// + city
// + "-" + ((String[]) mDistrictMap.get(city))[mDistrictPicker.getValue()]);
/*locate.setText(provinceModel.getName() + "-"
+ cityModel.getName()
+ (districtModel == null ? "" : ("-" + districtModel.getName())));*/
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).show();
return ad;
}
void init() {
mProvicePicker.setWrapSelectorWheel(false);
mProvicePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker numberPicker, int oldVal, int newVal) {
String proName = mProvinceDatas[newVal];
String[] pros = (String[]) mCitisDatasMap.get(proName);
mCityPicker.setDisplayedValues(null);
mDistrictPicker.setDisplayedValues(null);
setCityPickerTextSize((String[]) mCitisDatasMap.get(mProvinceDatas[newVal]));
setDisTrictPickerTextSize((String[]) (mDistrictMap.get(((String[]) mCitisDatasMap.get(mProvinceDatas[newVal]))[0])));
mCityPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
mDistrictPicker.setDisplayedValues(null);
setDisTrictPickerTextSize((String[]) mDistrictMap.get(mCityPicker.getDisplayedValues()[i1]));
}
});
mCityPicker.setWrapSelectorWheel(false);
}
});
mCityPicker.setWrapSelectorWheel(false);
mCityPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
mDistrictPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
setCityPickerTextSize((String[]) mCitisDatasMap.get(mProvinceDatas[0]));
setDisTrictPickerTextSize((String[]) mDistrictMap.get(((String[]) mCitisDatasMap.get(mProvinceDatas[0]))[0]));
}
private void setCityPickerTextSize(String[] cities) {
if (null != mCityPicker) {
mCityPicker.setMinValue(0);
mCityPicker.setMaxValue(cities.length - 1);
mCityPicker.setDisplayedValues(cities);
mProvicePicker.setMinValue(0);
mProvicePicker.setMaxValue(mProvinceDatas.length - 1);
mProvicePicker.setDisplayedValues(mProvinceDatas);
}
}
protected void setDisTrictPickerTextSize(String[] districts) {
if (mDistrictPicker != null) {
if (districts != null && districts.length > 0) {
mDistrictPicker.setMinValue(0);
mDistrictPicker.setMaxValue(districts.length > 0 ? districts.length - 1 : 0);
mDistrictPicker.setWrapSelectorWheel(false);
mDistrictPicker.setDisplayedValues(districts);
} else {
mDistrictPicker.setMinValue(0);
mDistrictPicker.setMaxValue(0);
mDistrictPicker.setWrapSelectorWheel(false);
mDistrictPicker.setDisplayedValues(new String[]{"无"});
}
}
}
/**
* 初始化省市数据
*/
protected void initProvinceDatas() {
new ResourceManager(new ResourceManager.Callable() {
@Override
public void onCall(List<ProvinceModel> list) {
mProvinceList = list;
// 初始化默认选中的省、市
if (mProvinceList != null && !mProvinceList.isEmpty()) {
mCurrentProviceName = mProvinceList.get(0).getName();
List<CityModel> cityList = mProvinceList.get(0).getChild();
if (cityList != null && !cityList.isEmpty()) {
mCurrentCityName = cityList.get(0).getName();
}
}
Log.d("wnw", list.size()+"");
mProvinceDatas = new String[mProvinceList.size()];
for (int i = 0; i < mProvinceList.size(); i++) {
// 遍历所有省的数据
mProvinceDatas[i] = mProvinceList.get(i).getName();
List<CityModel> cityList = mProvinceList.get(i).getChild();
String[] cityNames = new String[cityList.size()];
for (int j = 0; j < cityList.size(); j++) {
// 遍历省下面的所有市的数据
cityNames[j] = cityList.get(j).getName();
List<DistrictModel> districtList = cityList.get(j).getChild();
if (districtList != null && districtList.size() > 0) {
String[] districtNames = new String[districtList.size()];
for (int d = 0; d < districtList.size(); d++) {
districtNames[d] = districtList.get(d).getName();
}
mDistrictMap.put(cityList.get(j).getName(), districtNames);
}
}
// 省-市的数据,保存到mCitisDatasMap
mCitisDatasMap.put(mProvinceList.get(i).getName(), cityNames);
}
handler.sendMessage(new Message());
}
});
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
locatePickDialog();
}
};
public interface AddressPickedListener {
abstract void onAddressPicked(ProvinceModel province, CityModel city, DistrictModel district);
}
}
- 实体类
(1)实体类-省份
public class ProvinceModel {
private String id;
private String name;
private List<CityModel> child;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<CityModel> getChild() {
return child;
}
public void setChild(List<CityModel> child) {
this.child = child;
}
}
(2)实体类-城市
public class CityModel {
private String id;
private String name;
private String pid;
private List<DistrictModel> child;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public List<DistrictModel> getChild() {
return child;
}
public void setChild(List<DistrictModel> child) {
this.child = child;
}
}
(3)实体类-区(县)
public class DistrictModel implements Serializable {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public DistrictModel() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 布局文件
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/time_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<NumberPicker
android:id="@+id/monthpicker"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.5" />
<NumberPicker
android:id="@+id/hourpicker"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<NumberPicker
android:id="@+id/minuteicker"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
</FrameLayout>