android ios选择控件
2013-03-25 11:55:03 lovecluo 阅读数 3812

WheelView是一个开源的UI控件库,实现了滑轮滚动选择效果。

可以代替spinner来做选择控件,可以实现控件库中的OnWheelChangedListener接口实现两个wheelView控件的关联变化。

代码地址:http://download.csdn.net/detail/lovecluo/5178381

2017-04-21 13:49:00 weixin_34161029 阅读数 15
原文地址 https://github.com/mrfluency/Time-Selector
2268884-b2b73db4810f333a.png
Paste_Image.png

使用:

Android Studio中直接在 gradle中加入:

compile 'com.feezu.liuli:timeselector:1.1.3+' 

Eclipse下请下载源码(建议尽早迁移至Studio)
构造1:

TimeSelector(Context context, ResultHandler resultHandler, String startDate, String endDate)

参数说明:ResultHandler为选取时间后的回调 startDate,endDate为时间控件的可选起始时间和结束时间。

        TimeSelector timeSelector = new TimeSelector(this, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time) {
                Toast.makeText(getApplicationContext(), time, Toast.LENGTH_LONG).show();
            }
        }, "2015-11-22 17:34", "2015-12-1 15:20");

构造2:

    TimeSelector(Context context, ResultHandler resultHandler, String startDate, String endDate, String workStartTime, String workEndTime)

参数说明:传入workStartTime,workEndTime可选时间为起始时间和结束时间范围内的每日“时:分”的起始和结束时间,如限制可选时间为:朝9晚5。

        TimeSelector timeSelector = new TimeSelector(this, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time) {
                Toast.makeText(getApplicationContext(), time, Toast.LENGTH_LONG).show();
            }
        }, "2015-10-30 10:34", "2015-12-1 17:34","9:00","17:00");

使用: java <code>timeSelector.show();

1.1.0更新加入:

限制拨动 时和分 在show前调用:

java timeSelector.disScrollUnit(TimeSelector.SCROLLTYPE.HOUR, TimeSelector.SCROLLTYPE.MINUTE); 

设置显示模式: 年月日时分(默认)|年月日 在show前调用:

timeSelector.setMode(TimeSelector.MODE.YMDHM);//显示 年月日时分(默认);
timeSelector.setMode(TimeSelector.MODE.YMD);//只显示 年月日

1.1.1更新加入:

更新基础控件PickView,设置是否循环显示内容 可调用PickView实例的setIsLoop(boolean isLoop)方法,也可以在布局中如下使用

        <org.feezu.liuli.timeselector.view.PickerView
                    android:id="@+id/month_pv"
                    android:layout_width="0dp"
                    android:layout_height="160dp"
                    android:layout_weight="2"
                    app:isLoop="false" /> 

TimeSelector时间控件整体设置是否循环显示内容 在show()前调用:

java timeSelector.setIsLoop(false);//不设置时为true,即循环显示

转载于:https://www.jianshu.com/p/02ea8af4b8a5

2017-01-16 16:34:43 ruglcc 阅读数 580


https://github.com/lvfaqiang/Android-PickerView-master

最近根据项目需要,整理了一个相对比较全面的 WheelView 使用控件,借用之前看到的一句话来说,就是站在巨人肩膀上,进行了一些小调整。 
这里先贴上效果图

这里写图片描述

一般常用的时间选择格式,,单项选择,以及城市联动,这里基本都可以满足了。

这里把 单项选择,和 日期时间选择 给提出到 Util 类中,代码如下:

public class Util {

    /**
     * 时间选择回调
     */
    public interface TimerPickerCallBack {
        void onTimeSelect(String date);
    }

    /**
     * 弹出时间选择
     *
     * @param context
     * @param type     TimerPickerView 中定义的 选择时间类型
     * @param format   时间格式化
     * @param callBack 时间选择回调
     */
    public static void alertTimerPicker(Context context, TimePickerView.Type type, final String format, final TimerPickerCallBack callBack) {
        TimePickerView pvTime = new TimePickerView(context, type);
        //控制时间范围
        //        Calendar calendar = Calendar.getInstance();
        //        pvTime.setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR));
        pvTime.setTime(new Date());
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        //时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
//                        tvTime.setText(getTime(date));
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                callBack.onTimeSelect(sdf.format(date));
            }
        });
        pvTime.setTextSize(16);
        //弹出时间选择器
        pvTime.show();
    }


    /**
     * 底部滚轮点击事件回调
     */
    public interface OnWheelViewClick {
        void onClick(View view, int postion);
    }

    /**
     * 弹出底部滚轮选择
     *
     * @param context
     * @param list
     * @param click
     */
    public static void alertBottomWheelOption(Context context, ArrayList<?> list, final OnWheelViewClick click) {

        final PopupWindow popupWindow = new PopupWindow();

        View view = LayoutInflater.from(context).inflate(R.layout.layout_bottom_wheel_option, null);
        TextView tv_confirm = (TextView) view.findViewById(R.id.btnSubmit);
        final WheelView wv_option = (WheelView) view.findViewById(R.id.wv_option);
        wv_option.setAdapter(new ArrayWheelAdapter(list));
        wv_option.setCyclic(false);
        wv_option.setTextSize(16);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                click.onClick(view, wv_option.getCurrentItem());
            }
        });

        view.findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: 2016/8/11 0011 取消
                popupWindow.dismiss();
            }
        });
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int top = view.findViewById(R.id.ll_container).getTop();
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    int y = (int) motionEvent.getY();
                    if (y < top) {
                        popupWindow.dismiss();
                    }
                }
                return true;
            }
        });
        popupWindow.setContentView(view);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.showAtLocation(((ViewGroup) ((Activity) context).findViewById(android.R.id.content)).getChildAt(0), Gravity.CENTER, 0, 0);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 单项选择

    这里是模拟传入 ArrayList 形式的 String 类型 :

// 单项选择
        for (int i = 0; i <= 10; i++) {
            mList.add("模拟数据" + i);
        }

        tv_single_option.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Util.alertBottomWheelOption(MainActivity.this, mList, new Util.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int postion) {
                        Toast.makeText(MainActivity.this, mList.get(postion), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

补充:我们实际项目中用法可能是传入一个实体对象,那么我们到 WheelView 中找到设置显示内容的方法:

/**
     * 根据传进来的对象反射出getPickerViewText()方法,来获取需要显示的值
     * @param item
     * @return
     */
    private String getContentText(Object item) {
        String contentText = item.toString();
        try {
            Class<?> clz = item.getClass();
            Method m = clz.getMethod(GETPICKERVIEWTEXT);
            contentText = m.invoke(item, new Object[0]).toString();
        } catch (NoSuchMethodException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        } catch (Exception e){
        }
        return contentText;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

根据以上代码,可以看到如果是一个实体对象,那么就是通过对象内部定义的一个方法名为 GETPICKERVIEWTEXT(静态常量=”getPickerViewText”)的返回值来作为显示内容,

所以在创建对象的时候,要注意在对象内部添加一个 getPickerViewText()方法,代码如下:

public class TypeBean {

    private int id;
    private String name;

    public TypeBean(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //这个用来显示在PickerView上面的字符串,PickerView会通过反射获取getPickerViewText方法显示出来。
    public String getPickerViewText() {
        //这里还可以判断文字超长截断再提供显示
        return name;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 日期选择 
    这里是传入 选择日期类型,和 回调时间格式 就能直接得到想要的结果,
@Override
    public void onClick(View v) {
        String format = "";
        TimePickerView.Type type = null;
        switch (v.getId()) {
            case R.id.btn_ymdhm:
                type = TimePickerView.Type.ALL;
                format = "yyyy-MM-dd HH:mm";
                break;
            case R.id.btn_ymdh:
                type = TimePickerView.Type.YEAR_MONTH_DAY_HOUR;
                format = "yyyy-MM-dd HH";
                break;
            case R.id.btn_ymd:
                type = TimePickerView.Type.YEAR_MONTH_DAY;
                format = "yyyy-MM-dd";
                break;
            case R.id.btn_mdhm:
                type = TimePickerView.Type.MONTH_DAY_HOUR_MIN;
                format = "MM-dd HH:mm";
                break;
            case R.id.btn_hm:
                type = TimePickerView.Type.HOURS_MINS;
                format = "HH:mm";
                break;
            case R.id.btn_ym:
                type = TimePickerView.Type.YEAR_MONTH;
                format = "yyyy-MM";
                break;
        }
        Util.alertTimerPicker(this, type, format, new Util.TimerPickerCallBack() {
            @Override
            public void onTimeSelect(String date) {
                Toast.makeText(TestActivity.this, date, Toast.LENGTH_SHORT).show();
            }
        });

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 条件选择
private ArrayList<ProvinceBean> options1Items = new ArrayList<ProvinceBean>();
private ArrayList<ArrayList<String>> options2Items = new ArrayList<ArrayList<String>>();
private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<ArrayList<ArrayList<String>>>();

OptionsPickerView pvOptions;

private void showOptions(){
        //选项选择器
        pvOptions = new OptionsPickerView(this);
        // 初始化三个列表数据
        DataModel.initData(options1Items, options2Items, options3Items);

        //三级联动效果
        pvOptions.setPicker(options1Items, options2Items, options3Items, true);
        //设置选择的三级单位
//        pwOptions.setLabels("省", "市", "区");
        pvOptions.setTitle("选择城市");
        pvOptions.setCyclic(false, false, false);
        //设置默认选中的三级项目
        //监听确定选择按钮
        pvOptions.setSelectOptions(1, 1, 1);
        pvOptions.setTextSize(18);
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()
                        + options2Items.get(options1).get(option2)
                        + options3Items.get(options1).get(option2).get(options3);
                tvOptions.setText(tx);
                vMasker.setVisibility(View.GONE);
            }
        });
        //点击弹出选项选择器
        tvOptions.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pvOptions.show();
            }
        });
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

基本使用就这些了,也没什么技术含量,只是作为常用工具整理,也希望能给大家带来方便。

感谢一下提供该组件源码的大神。

Demo地址

2016-08-28 01:22:44 lv_fq 阅读数 9223

最近根据项目需要,整理了一个相对比较全面的 WheelView 使用控件,借用之前看到的一句话来说,就是站在巨人肩膀上,进行了一些小调整。
这里先贴上效果图

这里写图片描述

一般常用的时间选择格式,,单项选择,以及城市联动,这里基本都可以满足了。

这里把 单项选择,和 日期时间选择 给提出到 Util 类中,代码如下:

public class Util {

    /**
     * 时间选择回调
     */
    public interface TimerPickerCallBack {
        void onTimeSelect(String date);
    }

    /**
     * 弹出时间选择
     *
     * @param context
     * @param type     TimerPickerView 中定义的 选择时间类型
     * @param format   时间格式化
     * @param callBack 时间选择回调
     */
    public static void alertTimerPicker(Context context, TimePickerView.Type type, final String format, final TimerPickerCallBack callBack) {
        TimePickerView pvTime = new TimePickerView(context, type);
        //控制时间范围
        //        Calendar calendar = Calendar.getInstance();
        //        pvTime.setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR));
        pvTime.setTime(new Date());
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        //时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
//                        tvTime.setText(getTime(date));
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                callBack.onTimeSelect(sdf.format(date));
            }
        });
        pvTime.setTextSize(16);
        //弹出时间选择器
        pvTime.show();
    }


    /**
     * 底部滚轮点击事件回调
     */
    public interface OnWheelViewClick {
        void onClick(View view, int postion);
    }

    /**
     * 弹出底部滚轮选择
     *
     * @param context
     * @param list
     * @param click
     */
    public static void alertBottomWheelOption(Context context, ArrayList<?> list, final OnWheelViewClick click) {

        final PopupWindow popupWindow = new PopupWindow();

        View view = LayoutInflater.from(context).inflate(R.layout.layout_bottom_wheel_option, null);
        TextView tv_confirm = (TextView) view.findViewById(R.id.btnSubmit);
        final WheelView wv_option = (WheelView) view.findViewById(R.id.wv_option);
        wv_option.setAdapter(new ArrayWheelAdapter(list));
        wv_option.setCyclic(false);
        wv_option.setTextSize(16);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                click.onClick(view, wv_option.getCurrentItem());
            }
        });

        view.findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: 2016/8/11 0011 取消
                popupWindow.dismiss();
            }
        });
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int top = view.findViewById(R.id.ll_container).getTop();
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    int y = (int) motionEvent.getY();
                    if (y < top) {
                        popupWindow.dismiss();
                    }
                }
                return true;
            }
        });
        popupWindow.setContentView(view);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.showAtLocation(((ViewGroup) ((Activity) context).findViewById(android.R.id.content)).getChildAt(0), Gravity.CENTER, 0, 0);
    }
}
  • 单项选择

    这里是模拟传入 ArrayList 形式的 String 类型 :

// 单项选择
        for (int i = 0; i <= 10; i++) {
            mList.add("模拟数据" + i);
        }

        tv_single_option.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Util.alertBottomWheelOption(MainActivity.this, mList, new Util.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int postion) {
                        Toast.makeText(MainActivity.this, mList.get(postion), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

补充:我们实际项目中用法可能是传入一个实体对象,那么我们到 WheelView 中找到设置显示内容的方法:

/**
     * 根据传进来的对象反射出getPickerViewText()方法,来获取需要显示的值
     * @param item
     * @return
     */
    private String getContentText(Object item) {
        String contentText = item.toString();
        try {
            Class<?> clz = item.getClass();
            Method m = clz.getMethod(GETPICKERVIEWTEXT);
            contentText = m.invoke(item, new Object[0]).toString();
        } catch (NoSuchMethodException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        } catch (Exception e){
        }
        return contentText;
    }

根据以上代码,可以看到如果是一个实体对象,那么就是通过对象内部定义的一个方法名为 GETPICKERVIEWTEXT(静态常量=”getPickerViewText”)的返回值来作为显示内容,

所以在创建对象的时候,要注意在对象内部添加一个 getPickerViewText()方法,代码如下:

public class TypeBean {

    private int id;
    private String name;

    public TypeBean(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //这个用来显示在PickerView上面的字符串,PickerView会通过反射获取getPickerViewText方法显示出来。
    public String getPickerViewText() {
        //这里还可以判断文字超长截断再提供显示
        return name;
    }
}
  • 日期选择
    这里是传入 选择日期类型,和 回调时间格式 就能直接得到想要的结果,
@Override
    public void onClick(View v) {
        String format = "";
        TimePickerView.Type type = null;
        switch (v.getId()) {
            case R.id.btn_ymdhm:
                type = TimePickerView.Type.ALL;
                format = "yyyy-MM-dd HH:mm";
                break;
            case R.id.btn_ymdh:
                type = TimePickerView.Type.YEAR_MONTH_DAY_HOUR;
                format = "yyyy-MM-dd HH";
                break;
            case R.id.btn_ymd:
                type = TimePickerView.Type.YEAR_MONTH_DAY;
                format = "yyyy-MM-dd";
                break;
            case R.id.btn_mdhm:
                type = TimePickerView.Type.MONTH_DAY_HOUR_MIN;
                format = "MM-dd HH:mm";
                break;
            case R.id.btn_hm:
                type = TimePickerView.Type.HOURS_MINS;
                format = "HH:mm";
                break;
            case R.id.btn_ym:
                type = TimePickerView.Type.YEAR_MONTH;
                format = "yyyy-MM";
                break;
        }
        Util.alertTimerPicker(this, type, format, new Util.TimerPickerCallBack() {
            @Override
            public void onTimeSelect(String date) {
                Toast.makeText(TestActivity.this, date, Toast.LENGTH_SHORT).show();
            }
        });

    }
  • 条件选择
private ArrayList<ProvinceBean> options1Items = new ArrayList<ProvinceBean>();
private ArrayList<ArrayList<String>> options2Items = new ArrayList<ArrayList<String>>();
private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<ArrayList<ArrayList<String>>>();

OptionsPickerView pvOptions;

private void showOptions(){
        //选项选择器
        pvOptions = new OptionsPickerView(this);
        // 初始化三个列表数据
        DataModel.initData(options1Items, options2Items, options3Items);

        //三级联动效果
        pvOptions.setPicker(options1Items, options2Items, options3Items, true);
        //设置选择的三级单位
//        pwOptions.setLabels("省", "市", "区");
        pvOptions.setTitle("选择城市");
        pvOptions.setCyclic(false, false, false);
        //设置默认选中的三级项目
        //监听确定选择按钮
        pvOptions.setSelectOptions(1, 1, 1);
        pvOptions.setTextSize(18);
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()
                        + options2Items.get(options1).get(option2)
                        + options3Items.get(options1).get(option2).get(options3);
                tvOptions.setText(tx);
                vMasker.setVisibility(View.GONE);
            }
        });
        //点击弹出选项选择器
        tvOptions.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pvOptions.show();
            }
        });
    }

基本使用就这些了,也没什么技术含量,只是作为常用工具整理,也希望能给大家带来方便。

感谢一下提供该组件源码的大神。

Demo地址

2016-09-07 16:20:57 sunshine_mood 阅读数 3747

在ios7中有一种扁平风格的控件叫做分段选择控件UISegmentedControl,控件上横放或竖放着几个被简单线条隔开的按钮,每次点击能切换不同的按钮和按钮所对应的界面,比如qq客户端V6.5.3版本中消息页与电话页分离就是用的这种原理。但是很可惜的是Android系统并没有自带这种控件,不过我们也可以通过自定义RadioGroup实现该类效果,幸运的是Github上已有开源:https://github.com/Kaopiz/android-segmented-control

实现步骤如下:

第一步,在as中导入依赖:
dependencies {
compile ‘info.hoang8f:android-segmented:1.0.6’
}

第二步,在布局中引用控件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:segmentedgroup="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!--自定义的RadioButton单选按钮组-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimenActionBarHeight"
        android:background="@color/colorActionbar"
        android:gravity="center"
        android:minHeight="40dp">

        <info.hoang8f.android.segmented.SegmentedGroup
            android:id="@+id/mSegmentedGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:layout_marginRight="14dp"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            segmentedgroup:sc_border_width="1dp"
            segmentedgroup:sc_checked_text_color="@color/colorActionbar"
            segmentedgroup:sc_corner_radius="10dp"
            segmentedgroup:sc_tint_color="@color/colorWhite">

            <RadioButton
                android:id="@+id/radioButtonOne"
                style="@style/RadioButton"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="案例展示" />

            <RadioButton
                android:id="@+id/radioButtonTwo"
                style="@style/RadioButton"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="导师风采" />
        </info.hoang8f.android.segmented.SegmentedGroup>
    </RelativeLayout>

    <!--内容区-->
    <FrameLayout
        android:id="@+id/foundFrameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

第三步,在代码中绑定碎片(Fragment):

public class FoundActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener{

    private SegmentedGroup mSegmentedGroup;
    private RadioButton radioButtonOne, radioButtonTwo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_found);

        initWidget();//初始化组件
        initData();//初始化数据
        initEvent();//初始化是事件

    }

    private void initEvent() {
        radioButtonOne.setChecked(true);//默认选择第一个(案例展示碎片)
    }

    private void initData() {
    }

    private void initWidget() {
        mSegmentedGroup = (SegmentedGroup) findViewById(R.id.mSegmentedGroup);//控件组
        radioButtonOne = (RadioButton) findViewById(R.id.radioButtonOne);//单选按钮一
        radioButtonTwo = (RadioButton) findViewById(R.id.radioButtonTwo);//单选按钮二

        mSegmentedGroup.setTintColor(Color.WHITE);//设置默认线条颜色及背景色
        mSegmentedGroup.setOnCheckedChangeListener(this);//绑定单选按钮选择监听

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.radioButtonOne:
                FragmentManager fm = this.getSupportFragmentManager();//获得碎片管理器
                FragmentTransaction tr = fm.beginTransaction();//Transaction事物
                //将fragment碎片添加到对应的帧布局中
                tr.replace(R.id.foundFrameLayout, new CaseShowFragment());//案例展示碎片
                tr.commit();//提交
                break;
            case R.id.radioButtonTwo:
                FragmentManager fm2 = this.getSupportFragmentManager();
                FragmentTransaction tr2 = fm2.beginTransaction();
                tr2.replace(R.id.foundFrameLayout, new TutorStyleFragment());//导师咨询碎片
                tr2.commit();
                break;
        }
    }
}

好了,代码写到这里相信就已经达到了我们想要的效果,是不是很开ing呢?,哈哈,休息之余,不要忘记看看源码哦:

第四步,自定义RadioGroup源码分析:

public class SegmentedGroup extends RadioGroup {
    private int mMarginDp;
    private Resources resources = this.getResources();
    private int mTintColor;
    private int mCheckedTextColor = -1;
    private SegmentedGroup.LayoutSelector mLayoutSelector;
    private Float mCornerRadius;

    public SegmentedGroup(Context context) {
        super(context);
        this.mTintColor = this.resources.getColor(color.radio_button_selected_color);
        this.mMarginDp = (int)this.getResources().getDimension(dimen.radio_button_stroke_border);
        this.mCornerRadius = Float.valueOf(this.getResources().getDimension(dimen.radio_button_conner_radius));
        this.mLayoutSelector = new SegmentedGroup.LayoutSelector(this.mCornerRadius.floatValue());
    }

    private void initAttrs(AttributeSet attrs) {
        TypedArray typedArray = this.getContext().getTheme().obtainStyledAttributes(attrs, styleable.SegmentedGroup, 0, 0);

        try {
            this.mMarginDp = (int)typedArray.getDimension(styleable.SegmentedGroup_sc_border_width, this.getResources().getDimension(dimen.radio_button_stroke_border));
            this.mCornerRadius = Float.valueOf(typedArray.getDimension(styleable.SegmentedGroup_sc_corner_radius, this.getResources().getDimension(dimen.radio_button_conner_radius)));
            this.mTintColor = typedArray.getColor(styleable.SegmentedGroup_sc_tint_color, this.getResources().getColor(color.radio_button_selected_color));
            this.mCheckedTextColor = typedArray.getColor(styleable.SegmentedGroup_sc_checked_text_color, this.getResources().getColor(17170443));
        } finally {
            typedArray.recycle();
        }

    }

    public SegmentedGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mTintColor = this.resources.getColor(color.radio_button_selected_color);
        this.mMarginDp = (int)this.getResources().getDimension(dimen.radio_button_stroke_border);
        this.mCornerRadius = Float.valueOf(this.getResources().getDimension(dimen.radio_button_conner_radius));
        this.initAttrs(attrs);
        this.mLayoutSelector = new SegmentedGroup.LayoutSelector(this.mCornerRadius.floatValue());
    }

    protected void onFinishInflate() {
        super.onFinishInflate();
        this.updateBackground();
    }

    public void setTintColor(int tintColor) {
        this.mTintColor = tintColor;
        this.updateBackground();
    }

    public void setTintColor(int tintColor, int checkedTextColor) {
        this.mTintColor = tintColor;
        this.mCheckedTextColor = checkedTextColor;
        this.updateBackground();
    }

    public void updateBackground() {
        int count = super.getChildCount();

        for(int i = 0; i < count; ++i) {
            View child = this.getChildAt(i);
            this.updateBackground(child);
            if(i == count - 1) {
                break;
            }

            LayoutParams initParams = (LayoutParams)child.getLayoutParams();
            LayoutParams params = new LayoutParams(initParams.width, initParams.height, initParams.weight);
            if(this.getOrientation() == 0) {
                params.setMargins(0, 0, -this.mMarginDp, 0);
            } else {
                params.setMargins(0, 0, 0, -this.mMarginDp);
            }

            child.setLayoutParams(params);
        }

    }

    private void updateBackground(View view) {
        int checked = this.mLayoutSelector.getSelected();
        int unchecked = this.mLayoutSelector.getUnselected();
        ColorStateList colorStateList = new ColorStateList(new int[][]{{16842919}, {-16842919, -16842912}, {-16842919, 16842912}}, new int[]{-7829368, this.mTintColor, this.mCheckedTextColor});
        ((Button)view).setTextColor(colorStateList);
        Drawable checkedDrawable = this.resources.getDrawable(checked).mutate();
        Drawable uncheckedDrawable = this.resources.getDrawable(unchecked).mutate();
        ((GradientDrawable)checkedDrawable).setColor(this.mTintColor);
        ((GradientDrawable)checkedDrawable).setStroke(this.mMarginDp, this.mTintColor);
        ((GradientDrawable)uncheckedDrawable).setStroke(this.mMarginDp, this.mTintColor);
        ((GradientDrawable)checkedDrawable).setCornerRadii(this.mLayoutSelector.getChildRadii(view));
        ((GradientDrawable)uncheckedDrawable).setCornerRadii(this.mLayoutSelector.getChildRadii(view));
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[]{-16842912}, uncheckedDrawable);
        stateListDrawable.addState(new int[]{16842912}, checkedDrawable);
        if(VERSION.SDK_INT >= 16) {
            view.setBackground(stateListDrawable);
        } else {
            view.setBackgroundDrawable(stateListDrawable);
        }

    }

    private class LayoutSelector {
        private int children;
        private int child;
        private final int SELECTED_LAYOUT;
        private final int UNSELECTED_LAYOUT;
        private float r;
        private final float r1;
        private final float[] rLeft;
        private final float[] rRight;
        private final float[] rMiddle;
        private final float[] rDefault;
        private final float[] rTop;
        private final float[] rBot;
        private float[] radii;

        public LayoutSelector(float cornerRadius) {
            this.SELECTED_LAYOUT = drawable.radio_checked;
            this.UNSELECTED_LAYOUT = drawable.radio_unchecked;
            this.r1 = TypedValue.applyDimension(1, 0.1F, SegmentedGroup.this.getResources().getDisplayMetrics());
            this.children = -1;
            this.child = -1;
            this.r = cornerRadius;
            this.rLeft = new float[]{this.r, this.r, this.r1, this.r1, this.r1, this.r1, this.r, this.r};
            this.rRight = new float[]{this.r1, this.r1, this.r, this.r, this.r, this.r, this.r1, this.r1};
            this.rMiddle = new float[]{this.r1, this.r1, this.r1, this.r1, this.r1, this.r1, this.r1, this.r1};
            this.rDefault = new float[]{this.r, this.r, this.r, this.r, this.r, this.r, this.r, this.r};
            this.rTop = new float[]{this.r, this.r, this.r, this.r, this.r1, this.r1, this.r1, this.r1};
            this.rBot = new float[]{this.r1, this.r1, this.r1, this.r1, this.r, this.r, this.r, this.r};
        }

        private int getChildren() {
            return SegmentedGroup.this.getChildCount();
        }

        private int getChildIndex(View view) {
            return SegmentedGroup.this.indexOfChild(view);
        }

        private void setChildRadii(int newChildren, int newChild) {
            if(this.children != newChildren || this.child != newChild) {
                this.children = newChildren;
                this.child = newChild;
                if(this.children == 1) {
                    this.radii = this.rDefault;
                } else if(this.child == 0) {
                    this.radii = SegmentedGroup.this.getOrientation() == 0?this.rLeft:this.rTop;
                } else if(this.child == this.children - 1) {
                    this.radii = SegmentedGroup.this.getOrientation() == 0?this.rRight:this.rBot;
                } else {
                    this.radii = this.rMiddle;
                }

            }
        }

        public int getSelected() {
            return this.SELECTED_LAYOUT;
        }

        public int getUnselected() {
            return this.UNSELECTED_LAYOUT;
        }

        public float[] getChildRadii(View view) {
            int newChildren = this.getChildren();
            int newChild = this.getChildIndex(view);
            this.setChildRadii(newChildren, newChild);
            return this.radii;
        }
    }
}

第五步,效果图:

这里写图片描述

没有更多推荐了,返回首页