三级联动(省市区)

CityPickerDialog.getInstance(mContext, cstr, new CityPickerDialog.CallBack() {
    @Override
    public void call(String proId, String ctyId,String cyId, String city,String cc) {
        provinceId=proId;
        cityId=ctyId;
        counyId=cyId;
        if (!cc.equals(cstr))
            cstr = cc;
        tv_district_text.setText(city);
    }

}).show();

CityPickerDialog类



/**
 * Created by wuqiqi on 2015/12/2.
 */
public class CityPickerDialog extends Dialog {
    private Button btn_finish, btn_cancel;
    private CityPicker picker;
    public static String provinceId = "", cityId = "", counyId = "";
    public static String cityStr = "",ccstr = "";
    private static CallBack callBack;
    private int preId = 0,cId = 0,couId = 0;

    public static final CityPickerDialog getInstance(Context context, String cc, CallBack callback) {
        CityPickerDialog dialog = new CityPickerDialog(context, R.style.dialog_style);
        callBack = callback;
        if (!TextUtils.isEmpty(cc)) {
            dialog.preId = Integer.valueOf(cc.substring(0, cc.indexOf("")));
            dialog.cId = Integer.valueOf(cc.substring(cc.indexOf("") + 1, cc.lastIndexOf("")));
            dialog.couId = Integer.valueOf(cc.substring(cc.lastIndexOf("") + 1));
        }
        return dialog;
    }

    public CityPickerDialog(Context context) {
        super(context);
    }

    public CityPickerDialog(Context context, int theme) {
        super(context, theme);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_city_picker);
        setCanceledOnTouchOutside(true);
        Window dialogWindow = this.getWindow();
        //设置位置
        dialogWindow.setGravity(Gravity.BOTTOM);
        //设置dialog的宽高属性
        dialogWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);
        btn_finish = (Button) findViewById(R.id.btn_finish);
        picker = (CityPicker) findViewById(R.id.citypicker);
        picker.setDefault(preId, cId, couId);
        provinceId = picker.provinceId;
        cityId = picker.cityId;
        counyId = picker.counyId;
        cityStr = picker.getCity_string();
        ccstr = picker.ids();
        picker.setOnSelectingListener(new CityPicker.OnSelectingListener() {
            @Override
            public void selected(boolean selected, String proId, String ciId, String coId, String ids) {
                if (selected) {
                    provinceId = proId;
                    cityId = ciId;
                    counyId = coId;
                    cityStr = picker.getCity_string();
                    ccstr = ids;
                }
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        btn_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callBack.call(provinceId, cityId, counyId, cityStr,ccstr);
                dismiss();
            }
        });
    }

    public interface CallBack {
        public void call(String proId, String ctyId, String counyId, String city,String cc);
    }
}

dialog_city_picker.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@color/color_ffffff"
    android:paddingBottom="10dp">

    <View
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:background="@color/color_e1e1e1" />

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">

        <Button
            android:id="@+id/btn_cancel"
            android:layout_gravity="left|center_vertical"
            android:layout_width="wrap_content"
            android:padding="5dp"
            android:text="取消"
            android:textSize="16dp"
            android:textColor="@color/color_6c6c6c"
            android:layout_height="fill_parent"
            android:background="@color/transparent"></Button>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/choose_city"
            android:textColor="@color/color_1ab469"
            android:layout_gravity="center"
            android:textSize="18dp" />

        <Button
            android:id="@+id/btn_finish"
            android:layout_width="wrap_content"
            android:text="确定"
            android:padding="5dp"
            android:textSize="16dp"
            android:textColor="@color/color_25b770"
            android:layout_gravity="right|center_vertical"
            android:layout_height="wrap_content"
            android:background="@color/transparent" />
    </FrameLayout>

    <View
        android:layout_width="fill_parent"
        android:layout_height="1px"
        android:background="@color/color_e1e1e1" />

    <com.bbtree.o2o.widget.citypicker.CityPicker
        android:id="@+id/citypicker"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        />


</LinearLayout>

CityPicker类


/**
 *  城市Picker
 *
 * @author wuqiqi
 *
 */
public class CityPicker extends LinearLayout {
   /** 滑动控件 */
   private ScrollerNumberPicker provincePicker;
   private ScrollerNumberPicker cityPicker;
   private ScrollerNumberPicker counyPicker;
   /** 选择监听 */
   private OnSelectingListener onSelectingListener;
   /** 刷新界面 */
   private static final int REFRESH_VIEW = 0x001;
   /** 临时日期 */
   private int tempProvinceIndex = -1;
   private int temCityIndex = -1;
   private int tempCounyIndex = -1;
   private Context context;
   private List<Cityinfo> province_list = new ArrayList<Cityinfo>();
   private HashMap<String, List<Cityinfo>> city_map = new HashMap<String, List<Cityinfo>>();
   private HashMap<String, List<Cityinfo>> couny_map = new HashMap<String, List<Cityinfo>>();
   private static ArrayList<String> province_list_code = new ArrayList<String>();
   private static ArrayList<String> city_list_code = new ArrayList<String>();
   private static ArrayList<String> couny_list_code = new ArrayList<String>();
    public static String provinceId, cityId, counyId;

   private CitycodeUtil citycodeUtil;
   private String city_code_string;
   private String city_string;

   public CityPicker(Context context, AttributeSet attrs) {
      super(context, attrs);
      this.context = context;
      getaddressinfo();
   }

   public CityPicker(Context context) {
      super(context);
      this.context = context;
      getaddressinfo();
   }

   // 获取城市信息
   private void getaddressinfo() {
      // 读取城市信息string
      province_list= (List<Cityinfo>) MemCache.getInstance().get("area0");
      if(ListUtils.getSize(province_list)==0){
         String area_str = FileUtil.readAssets(context, "area.json");
         JSONParser parser = new JSONParser();
         province_list = parser.getJSONParserResult(area_str, "area0");
         city_map = parser.getJSONParserResultArray(area_str, "area1");
         couny_map = parser.getJSONParserResultArray(area_str, "area2");
         MemCache.getInstance().put("area0",province_list);
         MemCache.getInstance().put("area1",city_map);
         MemCache.getInstance().put("area2",couny_map);
      }else{
         city_map= (HashMap<String, List<Cityinfo>>) MemCache.getInstance().get("area1");
         couny_map= (HashMap<String, List<Cityinfo>>) MemCache.getInstance().get("area2");
      }

   }

   public void setDefault(int provinceId, int cityId, int counyId) {
         this.pid = provinceId;
         this.cid = cityId;
         this.ccid = counyId;
      onFinishInflate();
   }

   public static class JSONParser {
      public ArrayList<String> province_list_code = new ArrayList<String>();
      public ArrayList<String> city_list_code = new ArrayList<String>();

      public List<Cityinfo> getJSONParserResult(String JSONString, String key) {
         List<Cityinfo> list = new ArrayList<Cityinfo>();
         JsonObject result = new JsonParser().parse(JSONString).getAsJsonObject().getAsJsonObject(key);

         Iterator iterator = result.entrySet().iterator();
         while (iterator.hasNext()) {
            Entry<String, JsonElement> entry = (Entry<String, JsonElement>) iterator.next();
            Cityinfo cityinfo = new Cityinfo();
            cityinfo.setCity_name(entry.getValue().getAsString());
            cityinfo.setId(entry.getKey());
            province_list_code.add(entry.getKey());
            list.add(cityinfo);
         }

         return list;
      }

      public HashMap<String, List<Cityinfo>> getJSONParserResultArray(String JSONString, String key) {
         HashMap<String, List<Cityinfo>> hashMap = new HashMap<String, List<Cityinfo>>();
         JsonObject result = new JsonParser().parse(JSONString).getAsJsonObject().getAsJsonObject(key);

         Iterator iterator = result.entrySet().iterator();
         while (iterator.hasNext()) {
            Entry<String, JsonElement> entry = (Entry<String, JsonElement>) iterator.next();
            List<Cityinfo> list = new ArrayList<Cityinfo>();
            JsonArray array = entry.getValue().getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    JsonArray array1 = array.get(i).getAsJsonArray();

                    for (int j = 0;j < array1.size();j++) {
                        JsonObject result1 = array1.get(j).getAsJsonObject();
                        Iterator iterator1 = result1.entrySet().iterator();
                        while (iterator1.hasNext()) {
                            Entry<String, JsonElement> entry1 = (Entry<String, JsonElement>) iterator1.next();
                            Cityinfo cityinfo1 = new Cityinfo();
                            cityinfo1.setCity_name(entry1.getValue().getAsString());
                            cityinfo1.setId(entry1.getKey());
                            city_list_code.add(entry1.getKey());

                            list.add(cityinfo1);
                        }
                    }

            }

            hashMap.put(entry.getKey(), list);
         }
         return hashMap;
      }
   }
   private int pid = 0,cid = 0,ccid = 0;
   @Override
   protected void onFinishInflate() {
      super.onFinishInflate();
      LayoutInflater.from(getContext()).inflate(R.layout.city_picker, this);
      citycodeUtil = CitycodeUtil.getSingleton();
      // 获取控件引用
      provincePicker = (ScrollerNumberPicker) findViewById(R.id.province);
      cityPicker = (ScrollerNumberPicker) findViewById(R.id.city);
      counyPicker = (ScrollerNumberPicker) findViewById(R.id.couny);

      provincePicker.setData(citycodeUtil.getProvince(province_list));
      provincePicker.setDefault(pid);
        provinceId = citycodeUtil.getProvince_list_code().get(pid);

      cityPicker.setData(citycodeUtil.getCity(city_map, citycodeUtil.getProvince_list_code().get(pid)));
      cityPicker.setDefault(cid);
        cityId = citycodeUtil.getCity_list_code().get(cid);

      counyPicker.setData(citycodeUtil.getCouny(couny_map, citycodeUtil.getCity_list_code().get(cid)));
      counyPicker.setDefault(ccid);
        counyId = citycodeUtil.getCouny_list_code().get(ccid);

      provincePicker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {
         @Override
         public void endSelect(int id, String text) {
            if (text.equals("") || text == null)
               return;
            if (tempProvinceIndex != id) {
                    provinceId = citycodeUtil.getProvince_list_code().get(id);
               pid = id;
               String selectDay = cityPicker.getSelectedText();
               if (selectDay == null || selectDay.equals(""))
                  return;
               String selectMonth = counyPicker.getSelectedText();
               if (selectMonth == null || selectMonth.equals(""))
                  return;
               // 城市数组
               cityPicker.setData(citycodeUtil.getCity(city_map, citycodeUtil.getProvince_list_code().get(id)));
               cityPicker.setDefault(0);
                    cityId = citycodeUtil.getCity_list_code().get(0);
               cid = 0;
               counyPicker.setData(citycodeUtil.getCouny(couny_map, citycodeUtil.getCity_list_code().get(0)));
               counyPicker.setDefault(0);
                    counyId = citycodeUtil.getCouny_list_code().get(0);
               ccid = 0;
               int lastDay = Integer.valueOf(provincePicker.getListSize());
               if (id > lastDay)
                  provincePicker.setDefault(lastDay - 1);
            }

            tempProvinceIndex = id;
            Message message = new Message();
            message.what = REFRESH_VIEW;
            handler.sendMessage(message);
         }

         @Override
         public void selecting(int id, String text) {
         }
      });

      cityPicker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {
         @Override
         public void endSelect(int id, String text) {
            if (text.equals("") || text == null)
               return;

            if (temCityIndex != id) {
                    cityId = citycodeUtil.getCity_list_code().get(id);
               cid = id;
               String selectDay = provincePicker.getSelectedText();
               if (selectDay == null || selectDay.equals(""))
                  return;
               String selectMonth = counyPicker.getSelectedText();
               if (selectMonth == null || selectMonth.equals(""))
                  return;
               counyPicker.setData(citycodeUtil.getCouny(couny_map, citycodeUtil.getCity_list_code().get(id)));
               counyPicker.setDefault(0);
                    counyId = citycodeUtil.getCouny_list_code().get(0);
               ccid = 0;
               int lastDay = Integer.valueOf(cityPicker.getListSize());
               if (id > lastDay)
                  cityPicker.setDefault(lastDay - 1);
            }

            temCityIndex = id;
            Message message = new Message();
            message.what = REFRESH_VIEW;
            handler.sendMessage(message);
         }

         @Override
         public void selecting(int id, String text) {
         }
      });

      counyPicker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {

         @Override
         public void endSelect(int id, String text) {
            if (text.equals("") || text == null)
               return;
            if (tempCounyIndex != id) {
                    counyId = citycodeUtil.getCouny_list_code().get(id);
               ccid = id;
               String selectDay = provincePicker.getSelectedText();
               if (selectDay == null || selectDay.equals(""))
                  return;
               String selectMonth = cityPicker.getSelectedText();
               if (selectMonth == null || selectMonth.equals(""))
                  return;
               // 城市数组
               city_code_string = citycodeUtil.getCouny_list_code().get(id);
               int lastDay = Integer.valueOf(counyPicker.getListSize());
               if (id > lastDay) {
                  counyPicker.setDefault(lastDay - 1);
               }
            }
            tempCounyIndex = id;
            Message message = new Message();
            message.what = REFRESH_VIEW;
            handler.sendMessage(message);
         }

         @Override
         public void selecting(int id, String text) {
         }
      });
   }

   Handler handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
         super.handleMessage(msg);
         switch (msg.what) {
         case REFRESH_VIEW:
            if (onSelectingListener != null)
               onSelectingListener.selected(true, provinceId, cityId, counyId, ids());
            break;
         }
      }

   };

   public void setOnSelectingListener(OnSelectingListener onSelectingListener) {
      this.onSelectingListener = onSelectingListener;
   }

   public String getCity_code_string() {
      return provinceId + "-" + cityId + "-" + counyId;
   }

   public String getCity_string() {
      city_string = provincePicker.getSelectedText() + " - " + cityPicker.getSelectedText() +  " - " + counyPicker.getSelectedText();
//        city_string = provincePicker.getSelectedText() + " - " + cityPicker.getSelectedText();
        return city_string;
   }
   public String ids(){
      StringBuffer sb = new StringBuffer();
      sb.append(pid).append("").append(cid).append("").append(ccid);
      return sb.toString();
   }

   public interface OnSelectingListener {
      public void selected(boolean selected, String provinceId, String cityId, String counyId, String ids);
   }
}

滑动选择类ScrollerNumberPicker


/**
 * 
 * 滑动选择
 *
 * @author wuqiqi
 *
 */
public class ScrollerNumberPicker extends View {
   /** 控件宽度 */
   private float controlWidth;
   /** 控件高度 */
   private float controlHeight;
   /** 是否滑动中 */
   private boolean isScrolling = false;
   /** 选择的内容 */
   private ArrayList<ItemObject> itemList = new ArrayList<ItemObject>();
   /** 设置数据 */
   private ArrayList<String> dataList = new ArrayList<String>();
   /** 按下的坐标 */
   private int downY;
   /** 按下的时间 */
   private long downTime = 0;
   /** 短促移动 */
   private long goonTime = 200;
   /** 短促移动距离 */
   private int goonDistence = 100;
   /** 画线画笔 */
   private Paint linePaint;
   /** 线的默认颜色 */
   private int lineColor = 0xff000000;
   /** 默认字体 */
   private float normalFont = 14.0f;
   /** 选中的时候字体 */
   private float selectedFont = 22.0f;
   /** 单元格高度 */
   private int unitHeight = 50;
   /** 显示多少个内容 */
   private int itemNumber = 7;
   /** 默认字体颜色 */
   private int normalColor = 0xff000000;
   /** 选中时候的字体颜色 */
   private int selectedColor = 0xffff0000;
   /** 蒙板高度 */
   private float maskHight = 48.0f;
   /** 选择监听 */
   private OnSelectListener onSelectListener;
   /** 是否可用 */
   private boolean isEnable = true;
   /** 刷新界面 */
   private static final int REFRESH_VIEW = 0x001;
   /** 移动距离 */
   private static final int MOVE_NUMBER = 5;
   /** 是否允许选空 */
   private boolean noEmpty = false;

   /** 正在修改数据,避免ConcurrentModificationException异常 */
   private boolean isClearing = false;

    /**
     * 选中itemText 后的显示的label;
     */
    private String label="";

   public ScrollerNumberPicker(Context context, AttributeSet attrs,
         int defStyle) {
      super(context, attrs, defStyle);
      // TODO Auto-generated constructor stub
      init(context, attrs);
      initData();
   }

   public ScrollerNumberPicker(Context context, AttributeSet attrs) {
      super(context, attrs);
      // TODO Auto-generated constructor stub
      init(context, attrs);
      initData();
   }

   public ScrollerNumberPicker(Context context) {
      super(context);
      // TODO Auto-generated constructor stub
      initData();
   }

   @Override
   public boolean onTouchEvent(MotionEvent event) {
      // TODO Auto-generated method stub

      if (!isEnable)
         return true;
      int y = (int) event.getY();
      switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
         isScrolling = true;
         downY = (int) event.getY();
         downTime = System.currentTimeMillis();
         break;
      case MotionEvent.ACTION_MOVE:
         actionMove(y - downY);
         onSelectListener();
         break;
      case MotionEvent.ACTION_UP:

         // 移动距离的绝对值
         int move = (y - downY);
         move = move > 0 ? move : move * (-1);
         // 判断段时间移动的距离
         if (System.currentTimeMillis() - downTime < goonTime
               && move > goonDistence) {
            goonMove(y - downY);
         } else {
            actionUp(y - downY);
         }
         noEmpty();
         isScrolling = false;
         break;
      default:
         break;
      }
      return true;
   }

   @Override
   protected void onDraw(Canvas canvas) {
      // TODO Auto-generated method stub
      super.onDraw(canvas);

      drawLine(canvas);
      drawList(canvas);
      drawMask(canvas);
   }

   private synchronized void drawList(Canvas canvas) {
      if (isClearing)
         return;
      try {
         for (ItemObject itemObject : itemList) {
            itemObject.drawSelf(canvas);
         }
      } catch (Exception e) {
         // TODO: handle exception
      }

   }

   @Override
   protected void onLayout(boolean changed, int left, int top, int right,
         int bottom) {
      // TODO Auto-generated method stub
      super.onLayout(changed, left, top, right, bottom);
   }

   @Override
   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      // TODO Auto-generated method stub
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);
      controlWidth = getWidth();
      if (controlWidth != 0) {
         setMeasuredDimension(getWidth(), itemNumber * unitHeight);
         controlWidth = getWidth();
      }

   }

   /**
    * 继续移动一定距离
    */
   private synchronized void goonMove(final int move) {
      new Thread(new Runnable() {

         @Override
         public void run() {
            // TODO Auto-generated method stub
            int distence = 0;
            while (distence < unitHeight * MOVE_NUMBER) {
               try {
                  Thread.sleep(5);
               } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               }
               actionThreadMove(move > 0 ? distence : distence * (-1));
               distence += 10;

            }
            actionUp(move > 0 ? distence - 10 : distence * (-1) + 10);
            noEmpty();
         }
      }).start();
   }

   /**
    * 不能为空,必须有选项
    */
   private void noEmpty() {
      if (!noEmpty)
         return;
      for (ItemObject item : itemList) {
         if (item.isSelected())
            return;
      }
      int move = (int) itemList.get(0).moveToSelected();
      if (move < 0) {
         defaultMove(move);
      } else {
         defaultMove((int) itemList.get(itemList.size() - 1)
               .moveToSelected());
      }
      for (ItemObject item : itemList) {
         if (item.isSelected()) {
            if (onSelectListener != null)
               onSelectListener.endSelect(item.id, item.itemText);
            break;
         }
      }
   }

   /**
    * 初始化数据
    */
   private void initData() {
      isClearing = true;
      itemList.clear();
      for (int i = 0; i < dataList.size(); i++) {
         ItemObject itmItemObject = new ItemObject();
         itmItemObject.id = i;
         itmItemObject.itemText = dataList.get(i);
         itmItemObject.x = 0;
         itmItemObject.y = i * unitHeight;
         itemList.add(itmItemObject);
      }
      isClearing = false;

   }

   /**
    * 移动的时候
    *
    * @param move
    */
   private void actionMove(int move) {
      for (ItemObject item : itemList) {
         item.move(move);
      }
      invalidate();
   }

   /**
    * 移动,线程中调用
    *
    * @param move
    */
   private void actionThreadMove(int move) {
      for (ItemObject item : itemList) {
         item.move(move);
      }
      Message rMessage = new Message();
      rMessage.what = REFRESH_VIEW;
      handler.sendMessage(rMessage);
   }

   /**
    * 松开的时候
    *
    * @param move
    */
   private void actionUp(int move) {
      int newMove = 0;
      if (move > 0) {
         for (int i = 0; i < itemList.size(); i++) {
            if (itemList.get(i).isSelected()) {
               newMove = (int) itemList.get(i).moveToSelected();
               if (onSelectListener != null)
                  onSelectListener.endSelect(itemList.get(i).id,
                        itemList.get(i).itemText);
               break;
            }
         }
      } else {
         for (int i = itemList.size() - 1; i >= 0; i--) {
            if (itemList.get(i).isSelected()) {
               newMove = (int) itemList.get(i).moveToSelected();
               if (onSelectListener != null)
                  onSelectListener.endSelect(itemList.get(i).id,
                        itemList.get(i).itemText);
               break;
            }
         }
      }
      for (ItemObject item : itemList) {
         item.newY(move + 0);
      }
      slowMove(newMove);
      Message rMessage = new Message();
      rMessage.what = REFRESH_VIEW;
      handler.sendMessage(rMessage);

   }

   /**
    * 缓慢移动
    *
    * @param move
    */
   private synchronized void slowMove(final int move) {
      new Thread(new Runnable() {

         @Override
         public void run() {
            // TODO Auto-generated method stub
            // 判断政府
            int m = move > 0 ? move : move * (-1);
            int i = move > 0 ? 1 : (-1);
            // 移动速度
            int speed = 1;
            while (true) {
               m = m - speed;
               if (m <= 0) {
                  for (ItemObject item : itemList) {
                     item.newY(m * i);
                  }
                  Message rMessage = new Message();
                  rMessage.what = REFRESH_VIEW;
                  handler.sendMessage(rMessage);
                  try {
                     Thread.sleep(2);
                  } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                  }
                  break;
               }
               for (ItemObject item : itemList) {
                  item.newY(speed * i);
               }
               Message rMessage = new Message();
               rMessage.what = REFRESH_VIEW;
               handler.sendMessage(rMessage);
               try {
                  Thread.sleep(2);
               } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
               }
            }
            for (ItemObject item : itemList) {
               if (item.isSelected()) {
                  if (onSelectListener != null)
                     onSelectListener.endSelect(item.id, item.itemText);
                  break;
               }
            }

         }
      }).start();
   }

   /**
    * 移动到默认位置
    *
    * @param move
    */
   private void defaultMove(int move) {
      for (ItemObject item : itemList) {
         item.newY(move);
      }
      Message rMessage = new Message();
      rMessage.what = REFRESH_VIEW;
      handler.sendMessage(rMessage);
   }

   /**
    * 滑动监听
    */
   private void onSelectListener() {
      if (onSelectListener == null)
         return;
      for (ItemObject item : itemList) {
         if (item.isSelected()) {
            onSelectListener.selecting(item.id, item.itemText);
         }
      }
   }

   /**
    * 绘制线条
    *
    * @param canvas
    */
   private void drawLine(Canvas canvas) {

      if (linePaint == null) {
         linePaint = new Paint();
         linePaint.setColor(lineColor);
         linePaint.setAntiAlias(true);
         linePaint.setStrokeWidth(1f);
      }

      canvas.drawLine(0, controlHeight / 2 - unitHeight / 2 + 2,
            controlWidth, controlHeight / 2 - unitHeight / 2 + 2, linePaint);
      canvas.drawLine(0, controlHeight / 2 + unitHeight / 2 - 2,
            controlWidth, controlHeight / 2 + unitHeight / 2 - 2, linePaint);
   }

   /**
    * 绘制遮盖板
    *
    * @param canvas
    */
   private void drawMask(Canvas canvas) {
      LinearGradient lg = new LinearGradient(0, 0, 0, maskHight, 0x00f2f2f2,
            0x00f2f2f2, TileMode.MIRROR);
      Paint paint = new Paint();
      paint.setShader(lg);
      canvas.drawRect(0, 0, controlWidth, maskHight, paint);

      LinearGradient lg2 = new LinearGradient(0, controlHeight - maskHight,
            0, controlHeight, 0x00f2f2f2, 0x00f2f2f2, TileMode.MIRROR);
      Paint paint2 = new Paint();
      paint2.setShader(lg2);
      canvas.drawRect(0, controlHeight - maskHight, controlWidth,
            controlHeight, paint2);

   }

   /**
    * 初始化,获取设置的属性
    *
    * @param context
    * @param attrs
    */
   private void init(Context context, AttributeSet attrs) {
      TypedArray attribute = context.obtainStyledAttributes(attrs,
            R.styleable.NumberPicker);
      unitHeight = (int) attribute.getDimension(
            R.styleable.NumberPicker_unitHight, 32);
      normalFont = attribute.getDimension(
            R.styleable.NumberPicker_normalTextSize, 14.0f);
      selectedFont = attribute.getDimension(
            R.styleable.NumberPicker_selecredTextSize, 22.0f);
      itemNumber = attribute.getInt(R.styleable.NumberPicker_itemNumber, 7);
      normalColor = attribute.getColor(
            R.styleable.NumberPicker_normalTextColor, 0xff000000);
      selectedColor = attribute.getColor(
            R.styleable.NumberPicker_selecredTextColor, 0xffff0000);
      lineColor = attribute.getColor(R.styleable.NumberPicker_lineColor,
            0xff000000);
      maskHight = attribute.getDimension(
            R.styleable.NumberPicker_maskHight, 48.0f);
      noEmpty = attribute.getBoolean(R.styleable.NumberPicker_noEmpty,
            false);
      isEnable = attribute.getBoolean(R.styleable.NumberPicker_isEnable,
            true);
      attribute.recycle();

      controlHeight = itemNumber * unitHeight;

   }

   /**
    * 设置数据
    *
    * @param data
    */
   public void setData(ArrayList<String> data) {
      this.dataList = data;
      initData();
   }

    public void setLabel(String label){
        this.label=label;
    }

   /**
    * 获取返回项
    *
    * @return
    */
   public int getSelected() {
      for (ItemObject item : itemList) {
         if (item.isSelected())
            return item.id;
      }
      return -1;
   }

   /**
    * 获取返回的内容
    *
    * @return
    */
   public String getSelectedText() {
      for (ItemObject item : itemList) {
         if (item.isSelected())
            return item.itemText;
      }
      return "";
   }

   /**
    * 是否正在滑动
    *
    * @return
    */
   public boolean isScrolling() {
      return isScrolling;
   }

   /**
    * 是否可用
    *
    * @return
    */
   public boolean isEnable() {
      return isEnable;
   }

   /**
    * 设置是否可用
    *
    * @param isEnable
    */
   public void setEnable(boolean isEnable) {
      this.isEnable = isEnable;
   }

   /**
    * 设置默认选项
    *
    * @param index
    */
   public void setDefault(int index) {
      float move = itemList.get(index).moveToSelected();
      defaultMove((int) move);
   }

   /**
    * 获取列表大小
    *
    * @return
    */
   public int getListSize() {
      if (itemList == null)
         return 0;
      return itemList.size();
   }

   /**
    * 获取某项的内容
    *
    * @param index
    * @return
    */
   public String getItemText(int index) {
      if (itemList == null)
         return "";
      return itemList.get(index).itemText;
   }

   /**
    * 监听
    *
    * @param onSelectListener
    */
   public void setOnSelectListener(OnSelectListener onSelectListener) {
      this.onSelectListener = onSelectListener;
   }

   @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

      @Override
      public void handleMessage(Message msg) {
         // TODO Auto-generated method stub
         super.handleMessage(msg);
         switch (msg.what) {
         case REFRESH_VIEW:
            invalidate();
            break;
         default:
            break;
         }
      }

   };

   /**
    * 单条内容
    *
    * @author zoudong
    */
   private class ItemObject {
      /** id */
      public int id = 0;
      /** 内容 */
      public String itemText = "";

      /** x坐标 */
      public int x = 0;
      /** y坐标 */
      public int y = 0;
      /** 移动距离 */
      public int move = 0;
      /** 字体画笔 */
      private Paint textPaint;
      /** 字体范围矩形 */
      private Rect textRect;

      public ItemObject() {
         super();
      }

      /**
       * 绘制自身
       *
       * @param canvas
       */
      public void drawSelf(Canvas canvas) {

         if (textPaint == null) {
            textPaint = new Paint();
            textPaint.setAntiAlias(true);
         }

         if (textRect == null)
            textRect = new Rect();

         // 判断是否被选择
         if (isSelected()) {
            textPaint.setColor(selectedColor);
            // 获取距离标准位置的距离
            float moveToSelect = moveToSelected();
            moveToSelect = moveToSelect > 0 ? moveToSelect : moveToSelect * (-1);
            // 计算当前字体大小
            float textSize = (float) normalFont + ((float) (selectedFont - normalFont) * (1.0f - (float) moveToSelect / (float) unitHeight));
            textPaint.setTextSize(textSize);
                // 返回包围整个字符串的最小的一个Rect区域
                textPaint.getTextBounds(itemText+" "+label, 0, itemText.length(), textRect);
         } else {
            textPaint.setColor(normalColor);
            textPaint.setTextSize(normalFont);
                // 返回包围整个字符串的最小的一个Rect区域
                textPaint.getTextBounds(itemText, 0, itemText.length(), textRect);
         }


         // 判断是否可视
         if (!isInView())
            return;

         // 绘制内容
            // 判断是否被选择
            if (isSelected()) {
                canvas.drawText(itemText+" "+label, x + controlWidth / 2 - textRect.width() / 2, y + move + unitHeight / 2 + textRect.height() / 2, textPaint);
            }else{
                canvas.drawText(itemText, x + controlWidth / 2 - textRect.width() / 2, y + move + unitHeight / 2 + textRect.height() / 2, textPaint);
            }
      }

      /**
       * 是否在可视界面内
       *
       * @return
       */
      public boolean isInView() {
         if (y + move > controlHeight
               || (y + move + unitHeight / 2 + textRect.height() / 2) < 0)
            return false;
         return true;
      }

      /**
       * 移动距离
       *
       * @param _move
       */
      public void move(int _move) {
         this.move = _move;
      }

      /**
       * 设置新的坐标
       *
       */
      public void newY(int _move) {
         this.move = 0;
         this.y = y + _move;
      }

      /**
       * 判断是否在选择区域内
       *
       * @return
       */
      public boolean isSelected() {
         if ((y + move) >= controlHeight / 2 - unitHeight / 2 + 2
               && (y + move) <= controlHeight / 2 + unitHeight / 2 - 2)
            return true;
         if ((y + move + unitHeight) >= controlHeight / 2 - unitHeight / 2
               + 2
               && (y + move + unitHeight) <= controlHeight / 2
                     + unitHeight / 2 - 2)
            return true;
         if ((y + move) <= controlHeight / 2 - unitHeight / 2 + 2
               && (y + move + unitHeight) >= controlHeight / 2
                     + unitHeight / 2 - 2)
            return true;
         return false;
      }

      /**
       * 获取移动到标准位置需要的距离
       */
      public float moveToSelected() {
         return (controlHeight / 2 - unitHeight / 2) - (y + move);
      }
   }

   /**
    * 选择监听监听
    *
    * @author zoudong
    *
    */
   public interface OnSelectListener {

      /**
       * 结束选择
       *
       * @param id
       * @param text
       */
      public void endSelect(int id, String text);

      /**
       * 选中的内容
       * 
       * @param id
       * @param text
       */
      public void selecting(int id, String text);

   }
}
最后需要在assets中配置area.json


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值