Android 地址选择器,实现省市区三级联动

最近项目里面用到了一个地址选择器,实现现在主流的WheelView滑动选择,整理了下,做了个Demo.废话不多说,直接上代码:

主布局:

[java]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:paddingBottom="@dimen/activity_vertical_margin"  
  7.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  8.     android:paddingRight="@dimen/activity_horizontal_margin"  
  9.     android:paddingTop="@dimen/activity_vertical_margin"  
  10.     tools:context="com.example.user.myapplication.MainActivity">  
  11.   
  12.     <TextView  
  13.         android:id="@+id/select_address_tv"  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:gravity="center"  
  17.         android:textSize="15sp"  
  18.         android:text="选择地址" />  
  19. </RelativeLayout>  
MainActivity:

[java]  view plain  copy
  1. package com.example.user.myapplication;  
  2.   
  3. import android.support.v7.app.AppCompatActivity;  
  4. import android.os.Bundle;  
  5. import android.view.Gravity;  
  6. import android.view.View;  
  7. import android.widget.TextView;  
  8. import android.widget.Toast;  
  9.   
  10. public class MainActivity extends AppCompatActivity {  
  11.     private TextView select_address_tv;  
  12.   
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.activity_main);  
  17.   
  18.         select_address_tv= (TextView) findViewById(R.id.select_address_tv);  
  19.         select_address_tv   .setOnClickListener(new View.OnClickListener() {  
  20.             @Override  
  21.             public void onClick(View v) {  
  22.                 ChangeAddressPopwindow mChangeAddressPopwindow = new ChangeAddressPopwindow(MainActivity.this);  
  23.                 mChangeAddressPopwindow.setAddress("广东""深圳""福田区");  
  24.                 mChangeAddressPopwindow.showAtLocation(select_address_tv, Gravity.BOTTOM, 00);  
  25.                 mChangeAddressPopwindow  
  26.                         .setAddresskListener(new ChangeAddressPopwindow.OnAddressCListener() {  
  27.   
  28.                             @Override  
  29.                             public void onClick(String province, String city, String area) {  
  30.                                 // TODO Auto-generated method stub  
  31.                                 Toast.makeText(MainActivity.this,  
  32.                                         province + "-" + city + "-" + area,  
  33.                                         Toast.LENGTH_LONG).show();  
  34.                                 select_address_tv.setText(province + city + area);  
  35.                             }  
  36.                         });  
  37.             }  
  38.         });  
  39.     }  
  40. }  
主要的类:
[java]  view plain  copy
  1. package com.example.user.myapplication;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.drawable.ColorDrawable;  
  5. import android.view.View;  
  6. import android.view.ViewGroup;  
  7. import android.widget.PopupWindow;  
  8. import android.widget.TextView;  
  9.   
  10. import com.example.user.myapplication.wheelview.OnWheelChangedListener;  
  11. import com.example.user.myapplication.wheelview.OnWheelScrollListener;  
  12. import com.example.user.myapplication.wheelview.WheelView;  
  13. import com.example.user.myapplication.wheelview.adapter.AbstractWheelTextAdapter1;  
  14.   
  15. import org.json.JSONArray;  
  16. import org.json.JSONException;  
  17. import org.json.JSONObject;  
  18.   
  19. import java.io.IOException;  
  20. import java.io.InputStream;  
  21. import java.util.ArrayList;  
  22. import java.util.HashMap;  
  23. import java.util.Map;  
  24.   
  25. public class ChangeAddressPopwindow extends PopupWindow implements View.OnClickListener {  
  26.   
  27.     private WheelView wvProvince;  
  28.     private WheelView wvCitys;  
  29.     private WheelView wvArea;  
  30.     private View lyChangeAddress;  
  31.     private View lyChangeAddressChild;  
  32.     private TextView btnSure;  
  33.     private TextView btnCancel;  
  34.   
  35.     private Context context;  
  36.     private JSONObject mJsonObj;  
  37.     /** 
  38.      * 所有省 
  39.      */  
  40.     private String[] mProvinceDatas;  
  41.     /** 
  42.      * key - 省 value - 市s 
  43.      */  
  44.     private Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();  
  45.     /** 
  46.      * key - 市 values - 区s 
  47.      */  
  48.     private Map<String, String[]> mAreaDatasMap = new HashMap<String, String[]>();  
  49.   
  50.   
  51.     private ArrayList<String> arrProvinces = new ArrayList<String>();  
  52.     private ArrayList<String> arrCitys = new ArrayList<String>();  
  53.     private ArrayList<String> arrAreas = new ArrayList<String>();  
  54.     private AddressTextAdapter provinceAdapter;  
  55.     private AddressTextAdapter cityAdapter;  
  56.     private AddressTextAdapter areaAdapter;  
  57.   
  58.     private String strProvince = "广东";  
  59.     private String strCity = "深圳";  
  60.     private String strArea = "福田区";  
  61.     private OnAddressCListener onAddressCListener;  
  62.   
  63.     private int maxsize = 14;  
  64.     private int minsize = 12;  
  65.   
  66.     public ChangeAddressPopwindow(final Context context) {  
  67.         super(context);  
  68.         this.context = context;  
  69.         View view=View.inflate(context,R.layout.edit_changeaddress_pop_layout,null);  
  70.   
  71.         wvProvince = (WheelView) view.findViewById(R.id.wv_address_province);  
  72.         wvCitys = (WheelView) view.findViewById(R.id.wv_address_city);  
  73.         wvArea = (WheelView)view. findViewById(R.id.wv_address_area);  
  74.         lyChangeAddress = view.findViewById(R.id.ly_myinfo_changeaddress);  
  75.         lyChangeAddressChild = view.findViewById(R.id.ly_myinfo_changeaddress_child);  
  76.         btnSure = (TextView) view.findViewById(R.id.btn_myinfo_sure);  
  77.         btnCancel = (TextView)view. findViewById(R.id.btn_myinfo_cancel);  
  78.   
  79.   
  80.         //设置SelectPicPopupWindow的View  
  81.         this.setContentView(view);  
  82.         //设置SelectPicPopupWindow弹出窗体的宽  
  83.         this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);  
  84.         //设置SelectPicPopupWindow弹出窗体的高  
  85.         this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);  
  86.         //设置SelectPicPopupWindow弹出窗体可点击  
  87.         this.setFocusable(true);  
  88.         //设置SelectPicPopupWindow弹出窗体动画效果  
  89. //      this.setAnimationStyle(R.style.AnimBottom);  
  90.         //实例化一个ColorDrawable颜色为半透明  
  91.         ColorDrawable dw = new ColorDrawable(0xb0000000);  
  92.         //设置SelectPicPopupWindow弹出窗体的背景  
  93.         this.setBackgroundDrawable(dw);  
  94.   
  95.         lyChangeAddressChild.setOnClickListener(this);  
  96.         btnSure.setOnClickListener(this);  
  97.         btnCancel.setOnClickListener(this);  
  98.   
  99.         initJsonData();  
  100.         initDatas();  
  101.   
  102.   
  103.         initProvinces();  
  104.         provinceAdapter = new AddressTextAdapter(context, arrProvinces, getProvinceItem(strProvince), maxsize, minsize);  
  105.         wvProvince.setVisibleItems(5);  
  106.         wvProvince.setViewAdapter(provinceAdapter);  
  107.         wvProvince.setCurrentItem(getProvinceItem(strProvince));  
  108.   
  109.         initCitys(mCitisDatasMap.get(strProvince));  
  110.         cityAdapter = new AddressTextAdapter(context, arrCitys, getCityItem(strCity), maxsize, minsize);  
  111.         wvCitys.setVisibleItems(5);  
  112.         wvCitys.setViewAdapter(cityAdapter);  
  113.         wvCitys.setCurrentItem(getCityItem(strCity));  
  114.   
  115.         initAreas(mAreaDatasMap.get(strCity));  
  116.         areaAdapter = new AddressTextAdapter(context, arrAreas, getAreaItem(strArea), maxsize, minsize);  
  117.         wvArea.setVisibleItems(5);  
  118.         wvArea.setViewAdapter(areaAdapter);  
  119.         wvArea.setCurrentItem(getAreaItem(strArea));  
  120.   
  121.         wvProvince.addChangingListener(new OnWheelChangedListener() {  
  122.   
  123.             @Override  
  124.             public void onChanged(WheelView wheel, int oldValue, int newValue) {  
  125.                 // TODO Auto-generated method stub  
  126.                 String currentText = (String) provinceAdapter.getItemText(wheel.getCurrentItem());  
  127.                 strProvince = currentText;  
  128.                 setTextviewSize(currentText, provinceAdapter);  
  129.   
  130.                 String[] citys = mCitisDatasMap.get(currentText);  
  131.                 initCitys(citys);  
  132.                 cityAdapter = new AddressTextAdapter(context, arrCitys, 0, maxsize, minsize);  
  133.                 wvCitys.setVisibleItems(5);  
  134.                 wvCitys.setViewAdapter(cityAdapter);  
  135.                 wvCitys.setCurrentItem(0);  
  136.                 setTextviewSize("0", cityAdapter);  
  137.   
  138.                 //根据市,地区联动  
  139.                 String[] areas = mAreaDatasMap.get(citys[0]);  
  140.                 initAreas(areas);  
  141.                 areaAdapter = new AddressTextAdapter(context, arrAreas, 0, maxsize, minsize);  
  142.                 wvArea.setVisibleItems(5);  
  143.                 wvArea.setViewAdapter(areaAdapter);  
  144.                 wvArea.setCurrentItem(0);  
  145.                 setTextviewSize("0", areaAdapter);  
  146.             }  
  147.         });  
  148.   
  149.         wvProvince.addScrollingListener(new OnWheelScrollListener() {  
  150.   
  151.             @Override  
  152.             public void onScrollingStarted(WheelView wheel) {  
  153.                 // TODO Auto-generated method stub  
  154.   
  155.             }  
  156.   
  157.             @Override  
  158.             public void onScrollingFinished(WheelView wheel) {  
  159.                 // TODO Auto-generated method stub  
  160.                 String currentText = (String) provinceAdapter.getItemText(wheel.getCurrentItem());  
  161.                 setTextviewSize(currentText, provinceAdapter);  
  162.             }  
  163.         });  
  164.   
  165.         wvCitys.addChangingListener(new OnWheelChangedListener() {  
  166.   
  167.             @Override  
  168.             public void onChanged(WheelView wheel, int oldValue, int newValue) {  
  169.                 // TODO Auto-generated method stub  
  170.                 String currentText = (String) cityAdapter.getItemText(wheel.getCurrentItem());  
  171.                 strCity = currentText;  
  172.                 setTextviewSize(currentText, cityAdapter);  
  173.   
  174.                 //根据市,地区联动  
  175.                 String[] areas = mAreaDatasMap.get(currentText);  
  176.                 initAreas(areas);  
  177.                 areaAdapter = new AddressTextAdapter(context, arrAreas, 0, maxsize, minsize);  
  178.                 wvArea.setVisibleItems(5);  
  179.                 wvArea.setViewAdapter(areaAdapter);  
  180.                 wvArea.setCurrentItem(0);  
  181.                 setTextviewSize("0", areaAdapter);  
  182.   
  183.   
  184.             }  
  185.         });  
  186.   
  187.         wvCitys.addScrollingListener(new OnWheelScrollListener() {  
  188.   
  189.             @Override  
  190.             public void onScrollingStarted(WheelView wheel) {  
  191.                 // TODO Auto-generated method stub  
  192.   
  193.             }  
  194.   
  195.             @Override  
  196.             public void onScrollingFinished(WheelView wheel) {  
  197.                 // TODO Auto-generated method stub  
  198.                 String currentText = (String) cityAdapter.getItemText(wheel.getCurrentItem());  
  199.                 setTextviewSize(currentText, cityAdapter);  
  200.             }  
  201.         });  
  202.   
  203.         wvArea.addChangingListener(new OnWheelChangedListener() {  
  204.   
  205.             @Override  
  206.             public void onChanged(WheelView wheel, int oldValue, int newValue) {  
  207.                 // TODO Auto-generated method stub  
  208.                 String currentText = (String) areaAdapter.getItemText(wheel.getCurrentItem());  
  209.                 strArea = currentText;  
  210.                 setTextviewSize(currentText, cityAdapter);  
  211.             }  
  212.         });  
  213.   
  214.         wvArea.addScrollingListener(new OnWheelScrollListener() {  
  215.   
  216.             @Override  
  217.             public void onScrollingStarted(WheelView wheel) {  
  218.                 // TODO Auto-generated method stub  
  219.   
  220.             }  
  221.   
  222.             @Override  
  223.             public void onScrollingFinished(WheelView wheel) {  
  224.                 // TODO Auto-generated method stub  
  225.                 String currentText = (String) areaAdapter.getItemText(wheel.getCurrentItem());  
  226.                 setTextviewSize(currentText, areaAdapter);  
  227.             }  
  228.         });  
  229.   
  230.   
  231.     }  
  232.   
  233.   
  234.     private class AddressTextAdapter extends AbstractWheelTextAdapter1 {  
  235.         ArrayList<String> list;  
  236.   
  237.         protected AddressTextAdapter(Context context, ArrayList<String> list, int currentItem, int maxsize, int minsize) {  
  238.             super(context, R.layout.item_birth_year, NO_RESOURCE, currentItem, maxsize, minsize);  
  239.             this.list = list;  
  240.             setItemTextResource(R.id.tempValue);  
  241.         }  
  242.   
  243.         @Override  
  244.         public View getItem(int index, View cachedView, ViewGroup parent) {  
  245.             View view = super.getItem(index, cachedView, parent);  
  246.             return view;  
  247.         }  
  248.   
  249.         @Override  
  250.         public int getItemsCount() {  
  251.             return list.size();  
  252.         }  
  253.   
  254.         @Override  
  255.         protected CharSequence getItemText(int index) {  
  256.             return list.get(index) + "";  
  257.         }  
  258.     }  
  259.   
  260.     /** 
  261.      * 设置字体大小 
  262.      *  
  263.      * @param curriteItemText 
  264.      * @param adapter 
  265.      */  
  266.     public void setTextviewSize(String curriteItemText, AddressTextAdapter adapter) {  
  267.         ArrayList<View> arrayList = adapter.getTestViews();  
  268.         int size = arrayList.size();  
  269.         String currentText;  
  270.         for (int i = 0; i < size; i++) {  
  271.             TextView textvew = (TextView) arrayList.get(i);  
  272.             currentText = textvew.getText().toString();  
  273.             if (curriteItemText.equals(currentText)) {  
  274.                 textvew.setTextSize(14);  
  275.             } else {  
  276.                 textvew.setTextSize(12);  
  277.             }  
  278.         }  
  279.     }  
  280.   
  281.     public void setAddresskListener(OnAddressCListener onAddressCListener) {  
  282.         this.onAddressCListener = onAddressCListener;  
  283.     }  
  284.   
  285.     @Override  
  286.     public void onClick(View v) {  
  287.         // TODO Auto-generated method stub  
  288.         if (v == btnSure) {  
  289.             if (onAddressCListener != null) {  
  290.                 onAddressCListener.onClick(strProvince, strCity,strArea);  
  291.             }  
  292.         } else if (v == btnCancel) {  
  293.   
  294.         } else if (v == lyChangeAddressChild) {  
  295.             return;  
  296.         } else {  
  297. //          dismiss();  
  298.         }  
  299.         dismiss();  
  300.     }  
  301.   
  302.     /** 
  303.      * 回调接口 
  304.      *  
  305.      * @author Administrator 
  306.      * 
  307.      */  
  308.     public interface OnAddressCListener {  
  309.         public void onClick(String province, String city, String area);  
  310.     }  
  311.   
  312.     /** 
  313.      * 从文件中读取地址数据 
  314.      */  
  315.     private void initJsonData() {  
  316.         try {  
  317.             StringBuffer sb = new StringBuffer();  
  318.             InputStream is = context.getClass().getClassLoader().getResourceAsStream("assets/" + "city.json");  
  319.             int len = -1;  
  320.             byte[] buf = new byte[1024];  
  321.             while ((len = is.read(buf)) != -1) {  
  322.                 sb.append(new String(buf, 0, len, "gbk"));  
  323.             }  
  324.             is.close();  
  325.             mJsonObj = new JSONObject(sb.toString());  
  326.         } catch (IOException e) {  
  327.             e.printStackTrace();  
  328.         } catch (JSONException e) {  
  329.             e.printStackTrace();  
  330.         }  
  331.     }  
  332.   
  333.     /** 
  334.      * 解析整个Json对象,完成后释放Json对象的内存 
  335.      */  
  336.     private void initDatas()  
  337.     {  
  338.         try  
  339.         {  
  340.             JSONArray jsonArray = mJsonObj.getJSONArray("citylist");  
  341.             mProvinceDatas = new String[jsonArray.length()];  
  342.             for (int i = 0; i < jsonArray.length(); i++)  
  343.             {  
  344.                 JSONObject jsonP = jsonArray.getJSONObject(i);// 每个省的json对象  
  345.                 String province = jsonP.getString("p");// 省名字  
  346.   
  347.                 mProvinceDatas[i] = province;  
  348.   
  349.                 JSONArray jsonCs = null;  
  350.                 try  
  351.                 {  
  352.                     /** 
  353.                      * Throws JSONException if the mapping doesn't exist or is 
  354.                      * not a JSONArray. 
  355.                      */  
  356.                     jsonCs = jsonP.getJSONArray("c");  
  357.                 } catch (Exception e1)  
  358.                 {  
  359.                     continue;  
  360.                 }  
  361.                 String[] mCitiesDatas = new String[jsonCs.length()];  
  362.                 for (int j = 0; j < jsonCs.length(); j++)  
  363.                 {  
  364.                     JSONObject jsonCity = jsonCs.getJSONObject(j);  
  365.                     String city = jsonCity.getString("n");// 市名字  
  366.                     mCitiesDatas[j] = city;  
  367.                     JSONArray jsonAreas = null;  
  368.                     try  
  369.                     {  
  370.                         /** 
  371.                          * Throws JSONException if the mapping doesn't exist or 
  372.                          * is not a JSONArray. 
  373.                          */  
  374.                         jsonAreas = jsonCity.getJSONArray("a");  
  375.                     } catch (Exception e)  
  376.                     {  
  377.                         continue;  
  378.                     }  
  379.   
  380.                     String[] mAreasDatas = new String[jsonAreas.length()];// 当前市的所有区  
  381.                     for (int k = 0; k < jsonAreas.length(); k++)  
  382.                     {  
  383.                         String area = jsonAreas.getJSONObject(k).getString("s");// 区域的名称  
  384.                         mAreasDatas[k] = area;  
  385.                     }  
  386.                     mAreaDatasMap.put(city, mAreasDatas);  
  387.                 }  
  388.   
  389.                 mCitisDatasMap.put(province, mCitiesDatas);  
  390.             }  
  391.   
  392.         } catch (JSONException e)  
  393.         {  
  394.             e.printStackTrace();  
  395.         }  
  396.         mJsonObj = null;  
  397.     }  
  398.   
  399.     /** 
  400.      * 初始化省会 
  401.      */  
  402.     public void initProvinces() {  
  403.         int length = mProvinceDatas.length;  
  404.         for (int i = 0; i < length; i++) {  
  405.             arrProvinces.add(mProvinceDatas[i]);  
  406.         }  
  407.     }  
  408.   
  409.     /** 
  410.      * 根据省会,生成该省会的所有城市 
  411.      *  
  412.      * @param citys 
  413.      */  
  414.     public void initCitys(String[] citys) {  
  415.         if (citys != null) {  
  416.             arrCitys.clear();  
  417.             int length = citys.length;  
  418.             for (int i = 0; i < length; i++) {  
  419.                 arrCitys.add(citys[i]);  
  420.             }  
  421.         } else {  
  422.             String[] city = mCitisDatasMap.get("广东");  
  423.             arrCitys.clear();  
  424.             int length = city.length;  
  425.             for (int i = 0; i < length; i++) {  
  426.                 arrCitys.add(city[i]);  
  427.             }  
  428.         }  
  429.         if (arrCitys != null && arrCitys.size() > 0  
  430.                 && !arrCitys.contains(strCity)) {  
  431.             strCity = arrCitys.get(0);  
  432.         }  
  433.     }  
  434.   
  435.     /** 
  436.      * 根据城市,生成该城市的所有地区 
  437.      * 
  438.      * @param areas 
  439.      */  
  440.     public void initAreas(String[] areas) {  
  441.         if (areas != null) {  
  442.             arrAreas.clear();  
  443.             int length = areas.length;  
  444.             for (int i = 0; i < length; i++) {  
  445.                 arrAreas.add(areas[i]);  
  446.             }  
  447.         } else {  
  448.             String[] area = mAreaDatasMap.get("深圳");  
  449.             arrAreas.clear();  
  450.             int length = area.length;  
  451.             for (int i = 0; i < length; i++) {  
  452.                 arrAreas.add(area[i]);  
  453.             }  
  454.         }  
  455.         if (arrAreas != null && arrAreas.size() > 0  
  456.                 && !arrAreas.contains(strArea)) {  
  457.             strArea = arrAreas.get(0);  
  458.         }  
  459.     }  
  460.   
  461.     /** 
  462.      * 初始化地点 
  463.      *  
  464.      * @param province 
  465.      * @param city 
  466.      */  
  467.     public void setAddress(String province, String city, String area) {  
  468.         if (province != null && province.length() > 0) {  
  469.             this.strProvince = province;  
  470.         }  
  471.         if (city != null && city.length() > 0) {  
  472.             this.strCity = city;  
  473.         }  
  474.   
  475.         if (area != null && area.length() > 0) {  
  476.             this.strArea = area;  
  477.         }  
  478.     }  
  479.   
  480.     /** 
  481.      * 返回省会索引,没有就返回默认“广东” 
  482.      *  
  483.      * @param province 
  484.      * @return 
  485.      */  
  486.     public int getProvinceItem(String province) {  
  487.         int size = arrProvinces.size();  
  488.         int provinceIndex = 0;  
  489.         boolean noprovince = true;  
  490.         for (int i = 0; i < size; i++) {  
  491.             if (province.equals(arrProvinces.get(i))) {  
  492.                 noprovince = false;  
  493.                 return provinceIndex;  
  494.             } else {  
  495.                 provinceIndex++;  
  496.             }  
  497.         }  
  498.         if (noprovince) {  
  499.             strProvince = "广东";  
  500.             return 18;  
  501.         }  
  502.         return provinceIndex;  
  503.     }  
  504.   
  505.     /** 
  506.      * 得到城市索引,没有返回默认“深圳” 
  507.      *  
  508.      * @param city 
  509.      * @return 
  510.      */  
  511.     public int getCityItem(String city) {  
  512.         int size = arrCitys.size();  
  513.         int cityIndex = 0;  
  514.         boolean nocity = true;  
  515.         for (int i = 0; i < size; i++) {  
  516.             System.out.println(arrCitys.get(i));  
  517.             if (city.equals(arrCitys.get(i))) {  
  518.                 nocity = false;  
  519.                 return cityIndex;  
  520.             } else {  
  521.                 cityIndex++;  
  522.             }  
  523.         }  
  524.         if (nocity) {  
  525.             strCity = "深圳";  
  526.             return 2;  
  527.         }  
  528.         return cityIndex;  
  529.     }  
  530.   
  531.     /** 
  532.      * 得到地区索引,没有返回默认“福田区” 
  533.      * 
  534.      * @param area 
  535.      * @return 
  536.      */  
  537.     public int getAreaItem(String area) {  
  538.         int size = arrAreas.size();  
  539.         int areaIndex = 0;  
  540.         boolean noarea = true;  
  541.         for (int i = 0; i < size; i++) {  
  542.             System.out.println(arrAreas.get(i));  
  543.             if (area.equals(arrAreas.get(i))) {  
  544.                 noarea = false;  
  545.                 return areaIndex;  
  546.             } else {  
  547.                 areaIndex++;  
  548.             }  
  549.         }  
  550.         if (noarea) {  
  551.             strArea = "福田区";  
  552.             return 1;  
  553.         }  
  554.         return areaIndex;  
  555.     }  
  556.   
  557.   
  558. }  
弹出框布局:

[java]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:id="@+id/ly_myinfo_changeaddress"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:background="#00000000"  
  7.     android:gravity="bottom"  
  8.     android:orientation="vertical" >  
  9.   
  10.     <LinearLayout  
  11.         android:id="@+id/ly_myinfo_changeaddress_child"  
  12.         android:layout_width="match_parent"  
  13.         android:layout_height="wrap_content"  
  14.         android:layout_alignParentBottom="true"  
  15.         android:background="#ffffff"  
  16.         android:orientation="vertical" >  
  17.   
  18.   
  19.         <RelativeLayout  
  20.             android:layout_width="match_parent"  
  21.             android:layout_height="44dp"  
  22.              >  
  23.   
  24.             <TextView  
  25.                 android:id="@+id/btn_myinfo_cancel"  
  26.                 android:layout_width="wrap_content"  
  27.                 android:layout_height="match_parent"  
  28.                 android:paddingLeft="12dp"  
  29.                 android:text="取消"  
  30.                 android:gravity="center"  
  31.                 android:layout_alignParentLeft="true"  
  32.                 android:layout_marginRight="15dip"  
  33.                 android:textColor="#e84515"  
  34.                 android:textSize="13sp" />  
  35.   
  36.   
  37.             <TextView  
  38.                 android:id="@+id/btn_myinfo_sure"  
  39.                 android:layout_width="wrap_content"  
  40.                 android:layout_height="match_parent"  
  41.                 android:layout_alignParentRight="true"  
  42.                 android:gravity="center"  
  43.                 android:text="完成"  
  44.                 android:textColor="#e84515"  
  45.                 android:paddingRight="12dp"  
  46.                 android:textSize="12sp" />  
  47.   
  48.         </RelativeLayout>  
  49.   
  50.         <View android:layout_width="match_parent"  
  51.             android:layout_height="1dp"  
  52.             android:background="#d8d8d8"/>  
  53.   
  54.         <LinearLayout  
  55.             android:layout_width="match_parent"  
  56.             android:layout_height="160dip"  
  57.             android:orientation="horizontal"  
  58.             android:gravity="center_vertical">  
  59.             <com.example.user.myapplication.wheelview.WheelView  
  60.                 android:id="@+id/wv_address_province"  
  61.                 android:layout_width="0dip"  
  62.                 android:layout_weight="1"  
  63.                 android:layout_height="match_parent"  
  64.                 android:layout_gravity="center_vertical"  
  65.                 />  
  66.             <com.example.user.myapplication.wheelview.WheelView  
  67.                 android:id="@+id/wv_address_city"  
  68.                 android:layout_width="0dip"  
  69.                 android:layout_weight="1"  
  70.                 android:layout_height="match_parent"  
  71.                 android:layout_gravity="center_vertical"  
  72.                 />  
  73.   
  74.             <com.example.user.myapplication.wheelview.WheelView  
  75.                 android:id="@+id/wv_address_area"  
  76.                 android:layout_width="0dip"  
  77.                 android:layout_weight="1"  
  78.                 android:layout_height="match_parent"  
  79.                 android:layout_gravity="center_vertical"  
  80.                 />  
  81.         </LinearLayout>  
  82.   
  83.     </LinearLayout>  
  84.   
  85. </LinearLayout>  
运行效果图:

源代码下载

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1.省,市,区三级关联 2.地址数据本地化 3.自定义对话框 4.支付从xml文件,或对象文件加载 部分代码: package com.demo.selector; import java.io.InputStream; import com.address.selector.City; import com.address.selector.Country; import com.address.selector.Province; import com.address.selector.Region; import com.demo.address.R; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.AdapterView.OnItemSelectedListener; public class AddressSelectorDialog extends BaseDialog { /**省类型*/ private static final int INDEX_PROVINCE = 1; /**城市类型*/ private static final int INDEX_CITY = 2; /**区县类型*/ private static final int INDEX_REGION = 3; private static Country china = null; private Spinner spnProvince = null; private Spinner spnCity = null; private Spinner spnRegion = null; private ArrayAdapter dptProvince = null; private ArrayAdapter dptCity = null; private ArrayAdapter dptRegion = null; private SpinnerSelectedListener proListener = new SpinnerSelectedListener(); private SpinnerSelectedListener cityListener = new SpinnerSelectedListener(); private SpinnerSelectedListener regionListener = new SpinnerSelectedListener(); //当前选择地区的索引值 private int provinceId = -1; private int cityId = -1; private int regionId = -1; /**选择按钮*/ private Button btnSelect = null; /**回调用事件*/ private OnSelectorCancel selectorCancel = null; @Override public void init(Context context) { // TODO Auto-generated method stub this.context = context; dialog = new Dialog(this.context,R.style.CustomDialog); dialog.setContentView(R.layout.adress_selector); spnProvince = (Spinner)dialog.findViewById(R.id.spin_province); spnProvince.setTag(new Integer(INDEX_PROVINCE)); spnCity = (Spinner)dialog.findViewById(R.id.spin_city); spnCity.setTag(new Integer(INDEX_CITY)); spnRegion = (Spinner)dialog.findViewById(R.id.spin_region); spnRegion.setTag(new Integer(INDEX_REGION)); btnSelect = (Button)dialog.findViewById(R.id.btn_select); btnSelect.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub selectAddress(); } }); //当对话框隐藏后调用[回调事件] dialog.setOnCancelListener(new OnCancelListener(){ @Override public void onCancel(DialogInterface arg0) { // TODO Auto-generated method stub if (selectorCancel != null) { String proName = ""; String cityName = ""; String regName = ""; try { Province tmpPro = china.provinceLst.get(provinceId); proName = tmpPro.areaName; City tmpCity = tmpPro.cityLst.get(cityId); cityName = tmpCity.areaName; Region tmpReg = tmpCity.regionLst.get(regionId); regName = tmpReg.areaName; } catch (Exception e) { android.util.Log.e("selectorCancel???", e.getMessage()); } selectorCancel.onSelectorResult(proName, cityName, regName); } } }); //加载数据 if (china == null) { loadCountryAddressData(); } //加载完后,初始化适配器 initAdapters(); } @Override public void update(Object obj) { // TODO Auto-generated method stub } private void loadCountryAddressData() { try { /** * 反序化的包名,类名,版本ID必须一致,否则ClassNotFoundException */ InputStream stream = this.context.getAssets().open("china-city.obj"); china = Country.loadFromStream(stream); //mHandler.sendEmptyMessage(0); } catch (Exception e) { android.util.Log.e("error", e.getMessage()); } } class SpinnerSelectedListener implements OnItemSelectedListener{ @Override public void onItemSelected (AdapterView parent, View view, int position, long id) { // TODO Auto-generated method stub //android.util.Log.i("", String.format("[pos=%d]",position)); int index = (Integer)parent.getTag(); //ArrayAdapter obj = (ArrayAdapter)(parent.getAdapter()); //String value = obj.getItem(position); //android.util.Log.i("", "value=" + value); if (index == INDEX_PROVINCE) { provinceId = position; if (isValideProvinceIndex(provinceId)) { //改变城市选择 Province tmpProvince = china.provinceLst.get(provinceId); String lstNames[] = tmpProvince.listNames(); if (lstNames == null) { //没有城市,当然没区县 provinceId = -1; spnCity.setVisibility(View.INVISIBLE); regionId = -1; spnRegion.setVisibility(View.INVISIBLE); return ; } else { if (spnCity.getVisibility() == View.INVISIBLE) { spnCity.setVisibility(View.VISIBLE); } if (spnRegion.getVisibility() == View.INVISIBLE) { spnRegion.setVisibility(View.INVISIBLE); } } dptCity = new ArrayAdapter(context, android.R.layout.simple_spinner_item, lstNames); dptCity.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spnCity.setAdapter(dptCity); spnCity.setOnItemSelectedListener(cityListener); } } else if (index == INDEX_CITY) { cityId = position; if (isValideCityIndex(provinceId,cityId)) { //改变区选择 Province tmpProvince = china.provinceLst.get(provinceId); City tmpCity = tmpProvince.cityLst.get(cityId); String lstNames[] = tmpCity.listNames(); if (lstNames == null) { //没有区县 regionId = -1; spnRegion.setVisibility(View.INVISIBLE); return ; } else if (spnRegion.getVisibility() == View.INVISIBLE) { spnRegion.setVisibility(View.VISIBLE); } dptRegion = new ArrayAdapter(context, android.R.layout.simple_spinner_item, lstNames); dptRegion.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spnRegion.setAdapter(dptRegion); spnRegion.setOnItemSelectedListener(regionListener); } } else if (index == INDEX_REGION) { regionId = position; } } @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } } private void initAdapters() { dptProvince = new ArrayAdapter(this.context, android.R.layout.simple_spinner_item, china.listNames()); //设置下拉列表的风格 dptProvince.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //设置适配器 spnProvince.setAdapter(dptProvince); //设置侦听事件 spnProvince.setOnItemSelectedListener(proListener); } private boolean isValideProvinceIndex(int index) { return (china != null) && (index >= 0 && index = 0) && (china.provinceLst.get(provinceIndex).cityLst.size() > cityIndex); } return false; } private void selectAddress() { hide(); } /** * 调协回调事件 * @param selectorCancel */ public void setOnSelectorCancel(OnSelectorCancel selectorCancel) { this.selectorCancel = selectorCancel; } /** * 选择器关闭后,调用回调事件接口 */ public interface OnSelectorCancel { /** * @param proName 省份名 * @param cityName 城市名 * @param regName 区县名 */ public void onSelectorResult(String proName,String cityName,String regName); }; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值