地区选择控件杂记

1.json数据读取

 

 private void initJsonData() {
        try {
            StringBuffer sb = new StringBuffer();
            InputStream is = getAssets().open("city.json");//打开json数据
            byte[] by = new byte[is.available()];//转字节
            int len = -1;
            while ((len = is.read(by)) != -1) {
                sb.append(new String(by, 0, len, "gb2312"));//根据字节长度设置编码
            }
            is.close();//关闭流
            jsonObject = new JSONObject(sb.toString());//为json赋值
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

  

2.初始化省市区数据

private void initDatas() {
        try {
            JSONArray jsonArray = jsonObject.getJSONArray("citylist");//获取整个json数据
            allProv = new String[jsonArray.length()];//封装数据
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);//jsonArray转jsonObject
                String provStr = jsonP.getString("p");//获取所有的省
                allProv[i] = provStr;//封装所有的省
                JSONArray jsonCity = null;
                try {
                    jsonCity = jsonP.getJSONArray("c");//在所有的省中取出所有的市,转jsonArray
                } catch (Exception e) {
                    continue;
                }
                //所有的市
                String[] allCity = new String[jsonCity.length()];//所有市的长度
                for (int c = 0; c < jsonCity.length(); c++) {
                    JSONObject jsonCy = jsonCity.getJSONObject(c);//转jsonObject
                    String cityStr = jsonCy.getString("n");//取出所有的市
                    allCity[c] = cityStr;//封装市集合

                    JSONArray jsonArea = null;
                    try {
                        jsonArea = jsonCy.getJSONArray("a");//在从所有的市里面取出所有的区,转jsonArray
                    } catch (Exception e) {
                        continue;
                    }
                    String[] allArea = new String[jsonArea.length()];//所有的区
                    for (int a = 0; a < jsonArea.length(); a++) {
                        JSONObject jsonAa = jsonArea.getJSONObject(a);
                        String areaStr = jsonAa.getString("s");//获取所有的区
                        allArea[a] = areaStr;//封装起来
                    }
                    areaMap.put(cityStr, allArea);//某个市取出所有的区集合
                }
                cityMap.put(provStr, allCity);//某个省取出所有的市,
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        jsonObject = null;//清空所有的数据
    }

 

3.adapter

3.1更新adapter

provinceAdapter = new RegionAdapter(context, R.layout.region_item);
for (int i = 0; i < allProv.length; i++) {
    Region protemp = new Region(allProv[i], 0);
    prolist.add(protemp);
}
provinceAdapter.addAll(prolist);
/**
     * 根据当前的省,更新市和区的信息
     */
    private void updateCityAndArea(Object object) {
        String[] cities = cityMap.get(object);
        cityAdapter.clear();//清空adapter的数据
        citylist.clear();
        for (int i = 0; i < cities.length; i++) {
            Region citytemp = new Region(cities[i], 0);
            citylist.add(citytemp);//将这个列表“市”添加到adapter中
        }
        cityAdapter.addAll(citylist);
        cityAdapter.notifyDataSetChanged();//刷新
        updateArea(cities[0]);//更新区,没有市则默认第一个给它

    }

    //根据当前的市,更新区的信息
    private void updateArea(Object object) {
        String[] area = areaMap.get(object);
        areaAdapter.clear();//清空
        arealist.clear();
        if (area != null) {
            for (int i = 0; i < area.length; i++) {
                Region areatemp = new Region(area[i], 0);
                arealist.add(areatemp);
            }
            areaAdapter.addAll(arealist);//填入到这个列表
            areaAdapter.notifyDataSetChanged();//刷新
        }
    }

 

4.选中效果

//监听点击item事件
    private void setLVListener() {
        list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (zeroflag) {
                    case "province":
                        zeroflag = "city";
                        provinceName = provinceAdapter.getItem(position).getName();
                        printNike(prolist, provinceAdapter, position);
                        updateCityAndArea(provinceName);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Message message = new Message();
                                message.what = 1;
                                mHandler.sendMessageDelayed(message, 88);
                            }
                        }).start();
                        break;
                    case "city":
                        zeroflag = "area";
                        printNike(citylist, cityAdapter, position);//打勾
                        cityName = cityAdapter.getItem(position).getName();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Message message = new Message();
                                message.what = 2;
                                mHandler.sendMessageDelayed(message, 88);
                            }
                        }).start();

                        break;
                    case "area":
                        //兼容已有地址
                        if (areaMap.get(tv_city.getText().toString()) != null) {
                            zeroflag = "";
                            areaName = areaAdapter.getItem(position).getName();
                            tv_area.setText(areaName);
                            ll_area.setBackgroundColor(Color.parseColor("#f0eff4"));
                            tv_area.setTextColor(Color.parseColor("#50afff"));
                            printNike(arealist, areaAdapter, position);
                            rpdismiss();
                            //返回选择地区

                            act.changeTvre(tv_pro.getText().toString() + " " + tv_city.getText().toString() + " " + tv_area.getText().toString());
                        }
                        break;
                }


            }

        });

    }
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    list_view.setAdapter(cityAdapter);
                    tv_pro.setTextColor(Color.BLACK);
                    tv_pro.setText(provinceName);
                    ll_pro.setBackgroundColor(Color.parseColor("#f0eff4"));
                    ll_city.setBackgroundResource(R.drawable.line);
                    tv_city.setText("请选择");
                    tv_city.setTextColor(Color.parseColor("#50afff"));
                    break;
                case 2:
                    tv_city.setTextColor(Color.BLACK);
                    tv_city.setText(cityName);
                    ll_city.setBackgroundColor(Color.parseColor("#f0eff4"));
                    if (areaMap.get(cityName) != null) {//如果二级不为终点,弹出第三级
                        tv_area.setTextColor(Color.parseColor("#50afff"));
                        tv_area.setText("请选择");
                        ll_area.setBackgroundResource(R.drawable.line);
                        updateArea(cityName);
                        list_view.setAdapter(areaAdapter);
                    } else {//否则打勾退出
                        tv_city.setTextColor(Color.parseColor("#50afff"));

                        tv_area.setText("");

                        //返回选择地区
                        act.changeTvre(tv_pro.getText().toString() + " " + tv_city.getText().toString() );
                        rpdismiss();
                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

 

5.已有地区编辑

//监听TV事件
    private void setTVListener() {
        tv_pro.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zeroflag="province";
                outSelect(zeroflag);
                list_view.setAdapter(provinceAdapter);
            }
        });
        tv_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zeroflag="city";
                outSelect(zeroflag);
                updateCityAndArea(tv_pro.getText().toString());
                list_view.setAdapter(cityAdapter);
            }
        });
        tv_area.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zeroflag="area";
                outSelect(zeroflag);
                updateArea(tv_city.getText().toString());
                list_view.setAdapter(areaAdapter);
            }
        });
    }
//设置请选择效果
    private void outSelect(String sel){
        switch (sel){
            case "province":
                ll_pro.setBackgroundResource(R.drawable.line);
                tv_pro.setText("请选择");
                tv_pro.setTextColor(Color.parseColor("#50afff"));
                tv_city.setTextColor(Color.BLACK);
                tv_city.setText("");
                ll_city.setBackgroundColor(Color.parseColor("#f0eff4"));
                tv_area.setTextColor(Color.BLACK);
                tv_area.setText("");
                ll_area.setBackgroundColor(Color.parseColor("#f0eff4"));
                break;
            case "city":
                ll_city.setBackgroundResource(R.drawable.line);
                tv_city.setText("请选择");
                tv_city.setTextColor(Color.parseColor("#50afff"));
                tv_pro.setTextColor(Color.BLACK);
                ll_pro.setBackgroundColor(Color.parseColor("#f0eff4"));
                tv_area.setTextColor(Color.BLACK);
                tv_area.setText("");
                ll_area.setBackgroundColor(Color.parseColor("#f0eff4"));break;
            case "area":
                ll_area.setBackgroundResource(R.drawable.line);
                tv_area.setText("请选择");
                tv_area.setTextColor(Color.parseColor("#50afff"));
                tv_pro.setTextColor(Color.BLACK);
                ll_pro.setBackgroundColor(Color.parseColor("#f0eff4"));
                tv_city.setTextColor(Color.BLACK);
                ll_city.setBackgroundColor(Color.parseColor("#f0eff4"));break;

        }

    }
View Code

6.打勾

    /**
     * 打勾
     */
    private void printNike(List<Region> relist, RegionAdapter readapter, int position) {
        String tempname = relist.get(position).getName();//取原item标签,拼上图片替换原item
        Region tempregion = new Region(tempname, R.drawable.select);//加入图片资源
        tempregion.setIsend(true);
        relist.set(position, tempregion);
        readapter.clear();
        readapter.addAll(relist);
        readapter.notifyDataSetChanged();//刷新
    }
  @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Region region=getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
        TextView tv_region=(TextView) view.findViewById(R.id.tv_region);
        ImageView Iv_region=(ImageView) view.findViewById(R.id.iv_region);
        tv_region.setText(region.getName());
        if(region.getIsend()) {
            tv_region.setTextColor(Color.WHITE);
            view.setBackgroundColor(Color.parseColor("#50afff"));
        }
        Iv_region.setImageResource(region.getImageid());
        return view;
    }

7.数据传递

 private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BindMessageType.CLICK_INDUSTRY:
                    Bundle idata = msg.getData();
                    industryName = idata.getString("industryName");
                    updateIndustryView(industryName);
                    break;
                case BindMessageType.CLICK_AREA:
                    Bundle data = msg.getData();
                    province = data.getString("province");
                    city = data.getString("city");
                    area = data.getString("area");
                    updateAreaView(province, city, area);
                    break;
            }
        }
 /**
     * 发送消息
     *
     * @param messageType
     * @param province
     * @param city
     * @param area
     */
    private void sendMessage(int messageType, String province, String city, String area) {
        Message message = new Message();
        Bundle bundle = new Bundle();
        bundle.putString("province", province);
        bundle.putString("city", city);
        bundle.putString("area", area);
        message.setData(bundle);
        message.what = messageType;
        cHandler.sendMessage(message);
    }

 

posted @ 2017-09-11 11:08  Holyday  阅读(410)  评论(0编辑  收藏  举报