Android--省市区三级联动(dialog)

Android--省市区三级联动(dialog),第1张

概述目录gson框架效果图定义按钮逻辑文件自定义的dialog样式自定义view类CityPicker数据来源(area.json)自定义view(ScrollerNumberPicker类)省市县的布局文件(city_picker.xml)gson框架implementation'com.google.code.gson:gson:2.8.6'效果图定义按钮<Buttonand

目录gson框架效果图定义按钮@L_403_3@自定义的dialog样式自定义view类CityPicker数据来源(area.json)自定义view(ScrollerNumberPicker类)省市县的布局文件(city_picker.xml)

gson框架
implementation 'com.Google.code.gson:gson:2.8.6'
效果图

定义按钮
<button    androID:ID="@+ID/button"    androID:layout_wIDth="120dp"    androID:layout_height="60dp"    androID:text="选择地区"/>
逻辑文件
button button = findVIEwByID(R.ID.button);button.setonClickListener(new VIEw.OnClickListener() {            @OverrIDe            public voID onClick(VIEw v) {                AlertDialog.Builder builder=new AlertDialog.Builder(Info.this);                VIEw vIEw = LayoutInflater.from(Info.this).inflate(R.layout.addressdialog, null);                builder.setVIEw(vIEw);                linearLayout addressdialog_linearlayout = (linearLayout)vIEw.findVIEwByID(R.ID.addressdialog_linearlayout);                final ScrollerNumberPicker provincePicker = (ScrollerNumberPicker)vIEw.findVIEwByID(R.ID.province);                final ScrollerNumberPicker cityPicker = (ScrollerNumberPicker)vIEw.findVIEwByID(R.ID.city);                final ScrollerNumberPicker counyPicker = (ScrollerNumberPicker)vIEw.findVIEwByID(R.ID.couny);                final AlertDialog dialog = builder.show();                addressdialog_linearlayout.setonClickListener(new VIEw.OnClickListener() {                    @OverrIDe                    public voID onClick(VIEw v) {                        button.setText(provincePicker.getSelectedText()+cityPicker.getSelectedText()+counyPicker.getSelectedText());                        save.setVisibility(VIEw.VISIBLE);                        Log.i("kkkk",provincePicker.getSelectedText()+cityPicker.getSelectedText()+counyPicker.getSelectedText());                        dialog.dismiss();                    }                });            }        });
自定义的dialog样式
<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    androID:orIEntation="vertical"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent">    <!--顶部导航-->    <linearLayout        androID:ID="@+ID/myaddress_linerlayout"        androID:layout_wIDth="match_parent"        androID:layout_height="45dp"        androID:orIEntation="horizontal"        androID:gravity="center"        androID:background="#1290DC">        <linearLayout            androID:layout_wIDth="match_parent"            androID:layout_height="match_parent"            androID:layout_weight="1"            androID:orIEntation="vertical"            androID:gravity="left|center">            <TextVIEw                androID:layout_wIDth="wrap_content"                androID:layout_height="wrap_content"                androID:layout_margintop="3dp"                androID:layout_marginBottom="5dp"                androID:layout_marginleft="15dp"                androID:text="选择地区"                androID:textcolor="#fff"                androID:textSize="17dp"/>        </linearLayout>        <linearLayout            androID:ID="@+ID/addressdialog_linearlayout"            androID:layout_wIDth="match_parent"            androID:layout_height="match_parent"            androID:layout_weight="1"            androID:orIEntation="vertical"            androID:gravity="center|right">            <TextVIEw                androID:layout_wIDth="wrap_content"                androID:layout_height="wrap_content"                androID:layout_margintop="3dp"                androID:layout_marginBottom="5dp"                androID:layout_marginRight="15dp"                androID:text="确定"                androID:textcolor="#fff"                androID:textSize="17dp"/>        </linearLayout>    </linearLayout>    <linearLayout        androID:layout_below="@+ID/myaddress_linerlayout"        androID:layout_wIDth="match_parent"        androID:layout_height="180dp"        androID:orIEntation="horizontal"        androID:gravity="center"        androID:background="#ffff">        <com.czhoujunlv.drug.city.CityPicker            androID:ID="@+ID/citypicker"            androID:layout_wIDth="match_parent"            androID:layout_height="wrap_content"            androID:layout_gravity="center"            androID:gravity="center"            androID:orIEntation="vertical"/>    </linearLayout></relativeLayout>
自定义view类CityPicker
/** * 城市Picker * * @author * */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 CitycodeUtil citycodeUtil;    private String city_code_string;    private String city_string;    public CityPicker(Context context, AttributeSet attrs) {        super(context, attrs);        this.context = context;        getaddressinfo();        // Todo auto-generated constructor stub    }    public CityPicker(Context context) {        super(context);        this.context = context;        getaddressinfo();        // Todo auto-generated constructor stub    }    // 获取城市信息    private voID getaddressinfo() {        // Todo auto-generated method stub        // 读取城市信息string        JsONParser parser = new JsONParser();        String area_str = fileUtil.readAssets(context, "area.Json");        province_List = parser.getJsONParserResult(area_str, "area0");        city_map = parser.getJsONParserResultArray(area_str, "area1");        couny_map = parser.getJsONParserResultArray(area_str, "area2");    }    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()) {                @SuppressWarnings("unchecked")                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);            }            System.out.println(province_List_code.size());            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()) {                @SuppressWarnings("unchecked")                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++) {                    Cityinfo cityinfo = new Cityinfo();                    cityinfo.setCity_name(array.get(i).getAsJsonArray().get(0)                            .getAsstring());                    cityinfo.setID(array.get(i).getAsJsonArray().get(1)                            .getAsstring());                    city_List_code.add(array.get(i).getAsJsonArray().get(1)                            .getAsstring());                    List.add(cityinfo);                }                hashMap.put(entry.getKey(), List);            }            return hashMap;        }    }    @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(1);        cityPicker.setData(citycodeUtil.getCity(city_map, citycodeUtil                .getProvince_List_code().get(1)));        cityPicker.setDefault(1);        counyPicker.setData(citycodeUtil.getCouny(couny_map, citycodeUtil                .getCity_List_code().get(1)));        counyPicker.setDefault(1);        provincePicker.setonSelectListener(new ScrollerNumberPicker.OnSelectListener() {            @OverrIDe            public voID endSelect(int ID, String text) {                // Todo auto-generated method stub                Log.i("kkkk" ,ID + "text----->" + text);                if (text.equals("") || text == null)                    return;                if (tempProvinceIndex != ID) {                    System.out.println("endselect");                    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(1);                    counyPicker.setData(citycodeUtil.getCouny(couny_map,                            citycodeUtil.getCity_List_code().get(1)));                    counyPicker.setDefault(1);                    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) {                // Todo auto-generated method stub            }        });        cityPicker.setonSelectListener(new ScrollerNumberPicker.OnSelectListener() {            @OverrIDe            public voID endSelect(int ID, String text) {                // Todo auto-generated method stub                if (text.equals("") || text == null)                    return;                if (temCityIndex != 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(1);                    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) {                // Todo auto-generated method stub            }        });        counyPicker.setonSelectListener(new ScrollerNumberPicker.OnSelectListener() {            @OverrIDe            public voID endSelect(int ID, String text) {                // Todo auto-generated method stub                if (text.equals("") || text == null)                    return;                if (tempCounyIndex != 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) {                // Todo auto-generated method stub            }        });    }    @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:                    if (onSelectingListener != null)                        onSelectingListener.selected(true);                    break;                default:                    break;            }        }    };    public voID setonSelectingListener(OnSelectingListener onSelectingListener) {        this.onSelectingListener = onSelectingListener;    }    public String getCity_code_string() {        return city_code_string;    }    public String getCity_string() {        city_string = provincePicker.getSelectedText()                + cityPicker.getSelectedText() + counyPicker.getSelectedText();        return city_string;    }    public interface OnSelectingListener {        public voID selected(boolean selected);    }}
数据来源(area.Json)

文件下载以及放置位置

自定义view(ScrollerNumberPicker类)
/** * * 滑动选择 * * @author * */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;    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();    }    /**     * 获取返回项     *     * @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);            } else {                textPaint.setcolor(normalcolor);                textPaint.setTextSize(normalFont);            }            // 返回包围整个字符串的最小的一个Rect区域            textPaint.getTextBounds(itemText, 0, itemText.length(), textRect);            // 判断是否可视            if (!isInVIEw())                return;            // 绘制内容            canvas.drawText(itemText, x + controlWIDth / 2 - textRect.wIDth()                            / 2, y + move + unitHeight / 2 + textRect.height() / 2,                    textPaint);        }        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);    }}
省市县的布局文件(city_picker.xml)
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    xmlns:su="http://schemas.androID.com/apk/res-auto"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:gravity="center_horizontal"    androID:orIEntation="horizontal" >    <com.czhoujunlv.drug.city.ScrollerNumberPicker        androID:ID="@+ID/province"        androID:layout_wIDth="0dp"        androID:layout_height="wrap_content"        androID:layout_marginleft="1dp"        androID:layout_marginRight="1dp"        androID:layout_weight="1"        su:itemNumber="3"        su:linecolor="#ffff6000"        su:maskHight="32dp"        su:noEmpty="true"        su:normalTextcolor="#777"        su:normalTextSize="12sp"        su:selecredTextcolor="#ff000000"        su:selecredTextSize="13sp"        su:unitHight="50dp" />    <com.czhoujunlv.drug.city.ScrollerNumberPicker        androID:ID="@+ID/city"        androID:layout_wIDth="0dp"        androID:layout_height="wrap_content"        androID:layout_marginleft="1dp"        androID:layout_marginRight="1dp"        androID:layout_weight="1"        su:itemNumber="3"        su:linecolor="#ffff6000"        su:maskHight="32dp"        su:noEmpty="true"        su:normalTextcolor="#777"        su:normalTextSize="12sp"        su:selecredTextcolor="#ff000000"        su:selecredTextSize="13sp"        su:unitHight="50dp" />    <com.czhoujunlv.drug.city.ScrollerNumberPicker        androID:ID="@+ID/couny"        androID:layout_wIDth="0dp"        androID:layout_height="wrap_content"        androID:layout_marginleft="1dp"        androID:layout_marginRight="1dp"        androID:layout_weight="1"        su:itemNumber="3"        su:linecolor="#ffff6000"        su:maskHight="32dp"        su:noEmpty="true"        su:normalTextcolor="#777"        su:normalTextSize="12sp"        su:selecredTextcolor="#ff000000"        su:selecredTextSize="13sp"        su:unitHight="50dp" /></linearLayout>
总结

以上是内存溢出为你收集整理的Android--省市区三级联动(dialog)全部内容,希望文章能够帮你解决Android--省市区三级联动(dialog)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1048313.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存