Android笔记--一个上下滑动,还算看的过眼的日期、时间选择控件

效果图:

Android笔记--一个上下滑动,还算看的过眼的日期、时间选择控件_第1张图片Android笔记--一个上下滑动,还算看的过眼的日期、时间选择控件_第2张图片

还可以定制颜色:

Android笔记--一个上下滑动,还算看的过眼的日期、时间选择控件_第3张图片

主要特点是更灵活一些,网上有开源的,可是都封装好了,直接弹窗调用,而我的需求是相当于用控件一样嵌入到某一个布局中,所以自己写了一个,交互没这么炫酷的,勉强可用,话不多说,上代码:

调用:

PickerView  pvTime=(PickerView)findViewById(R.id.pv_time);
        pvTime.setOnPickerViewChangeListener(new PickerView.OnPickerViewListener() {
            @Override
            public void onChange(PickerView pickerView) {
                ALog.e(pickerView.getYear()+"年:"+pickerView.getMonth()+"月:"+pickerView.getDay()+"日"+
                        pickerView.getHour()+"时"+pickerView.getMinute()+"分");
            }
        });
        pvTime.setNameFormat(null,null,null,"时","分",null,null);//年月日时分秒毫秒,需要哪个填哪个,自由定制
        pvTime.setFontColor(0xff3EB9E6,0xffF90000);//设置滑动选中和非选中的字体颜色
        pvTime.setSeparateTvStyle(null,0xffDD8E0F);//设置下分隔字体的颜色大小,null为使用默认

布局:

<com.imxiaoyu.common.widget.PickerView
        android:id="@+id/pv_time"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

item源码:

package com.imxiaoyu.common.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.imxiaoyu.common.impl.OnStringListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义时间选择
 * Created by 庞光渝 on 2017/3/9.博客:https://my.oschina.net/u/1462828/blog
 */

public class PickerItemView extends View {

    /**
     * 变量
     */
    private List itemEntities;
    private float startY = 0;//记录手指按下时候的Y坐标
    private float itemHeight = 0;//每一个文本的高度(包括上下空白的地方)
    private float minFontSize;//最小的文字字体大小
    private float maxFontSize;//最大的文字字体大小
    private boolean isLoop = false;//是否循环
    private String lastValue;//
    private int defaultShowItemNum = 5;//默认显示的item个数,有改动的话不保证适配
    //用于根据高度设置最小最大文字的大小,范围2-80;
    private int minFontSizePercent = 35;
    private int maxFontSizePercent = 65;
    private int normalFontColor = 0xff999999;//正常的文字颜色
    private int pressFontColor = 0xff444444;//选中的文字颜色
    private String defaultValue;//默认显示的值
    private boolean isSetList = false;//是否已经设置了参数数组,用于判定设定值的时候是设置默认值还是直接设置值

    /**
     * 外部接口
     */
    private OnStringListener onPitchOnChangeListener;//拖动的时候,返回当前选中的

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

    public PickerItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PickerItemView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        itemHeight = getHeight() / defaultShowItemNum;
        minFontSize = itemHeight * minFontSizePercent / 100;
        maxFontSize = itemHeight * maxFontSizePercent / 100;
        if (itemEntities != null) {
            drawText(canvas);
        }
    }

    /**
     * 重写触摸监听
     *
     * @param event
     * @return
     */
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                float y = event.getY() - startY;
                startY = event.getY();
                onPitchOnBack();
                deviationY(y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                //手指抬起的时候,计算并偏移Y轴,相当于对齐一下位置,让被选中的那个保持在画布中间
                if (itemEntities != null && itemEntities.size() > 0) {
                    float intervalY = (itemEntities.get(0).getY()) % itemHeight;
                    intervalY = (intervalY + itemHeight * 2) % itemHeight;
                    if (intervalY >= itemHeight / 2) {
                        deviationY((itemHeight - intervalY));
                    } else {
                        deviationY(-intervalY);
                    }
                    invalidate();
                    onPitchOnBack();
                }
                break;
        }
        return true;
    }


    /**
     * 绘制文本
     *
     * @param canvas
     */
    private void drawText(Canvas canvas) {
        for (int i = 0; i < itemEntities.size(); i++) {
            ItemEntity itemEntity = itemEntities.get(i);
            if ((itemEntity.getY() > (-itemHeight)) && itemEntity.getY() < itemHeight * 6) {
                //在范围内,绘制出来
                float itemCoreY = itemEntity.getY() + itemHeight / 2;
                float itemCoreX = getWidth() / 2;
                float size = getFontSize(itemEntity.getY());
                int color = normalFontColor;
                if (size == maxFontSize) {
                    color = pressFontColor;
                }
                Bitmap bitmap = str2Bitmap(itemEntity.getValue(), (int) size, color);
                float x = itemCoreX - bitmap.getWidth() / 2;
                float y = itemCoreY - bitmap.getHeight() / 2;
                canvas.drawBitmap(bitmap, x, y, null);
            }
        }
    }

    /**
     * 将文本绘制成一个bitmap,并居中
     *
     * @param testString
     * @param size
     * @param txtColor
     * @return
     */
    public Bitmap str2Bitmap(String testString, int size, int txtColor) {
        float x = size * testString.length() + 1;
        float y = size + 1;
        Bitmap bmp = Bitmap.createBitmap((int) x, (int) y, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        Rect targetRect = new Rect(0, 0, (int) x, (int) y);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(size);
        paint.setColor(txtColor);
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        int baseline = (targetRect.bottom + targetRect.top - fontMetrics.bottom - fontMetrics.top) / 2;
        paint.setTextAlign(Paint.Align.CENTER);
        canvas.drawText(testString, targetRect.centerX(), baseline, paint);
        return bmp;
    }

    /**
     * Y 轴偏移,即移动
     *
     * @param y
     */
    private void deviationY(float y) {
        if (itemEntities == null || itemEntities.size() <= 0) {
            return;
        }
        //是否循环
        if (isLoop) {
            //判定头部
            if ((itemEntities.get(0).getY() + y) >= -itemHeight) {
                ItemEntity itemEntity = itemEntities.get(itemEntities.size() - 1);
                itemEntities.remove(itemEntities.size() - 1);
                itemEntity.setY(itemEntities.get(0).getY() - itemHeight);
                itemEntities.add(0, itemEntity);
            }
            //判定尾部
            if ((itemEntities.get(itemEntities.size() - 1).getY() + y) <= itemHeight * 6) {
                ItemEntity itemEntity = itemEntities.get(0);
                itemEntities.remove(0);
                itemEntity.setY(itemEntities.get(itemEntities.size() - 1).getY() + itemHeight);
                itemEntities.add(itemEntities.size(), itemEntity);
            }

            if ((itemEntities.get(0).getY() + y) >= -itemHeight || (itemEntities.get(itemEntities.size() - 1).getY() + y) <= itemHeight * 6) {
                //如果头部或者底部还存在空缺,则需要再度调整,因为目前还没完成偏移操作,所以再次调整的时候依旧可以传入y,直到全部递归调整完成之后才执行偏移
                deviationY(y);
                return;
            }
        } else {
            //不可以循环,上下到顶了就不给滑了
            if ((itemEntities.get(0).getY() + y) > itemHeight * 2) {
                return;
            }
            if ((itemEntities.get(itemEntities.size() - 1).getY() + y) < itemHeight * 2) {
                return;
            }
        }
        for (int i = 0; i < itemEntities.size(); i++) {
            itemEntities.get(i).setY(itemEntities.get(i).getY() + y);
        }
    }

    /**
     * 计算Y轴不同位置的需要映射的字体大小
     *
     * @param y
     * @return
     */
    private float getFontSize(float y) {
        y = y + itemHeight / 2;
        if (y <= itemHeight / 2 || y > 4.5 * itemHeight) {
            return minFontSize;
        }
        if (y > itemHeight / 2 && y < itemHeight * 2) {
            //慢慢大
            return (float) ((maxFontSize - minFontSize) * (y - (itemHeight / 2)) / (1.5 * itemHeight) + minFontSize);
        }
        if (y >= itemHeight * 2 && y <= itemHeight * 3) {
            return maxFontSize;
        }
        if (y > itemHeight * 3 && y <= 4.5 * itemHeight) {
            //慢慢小
            return (float) (maxFontSize - (maxFontSize - minFontSize) * (y - itemHeight * 3) / (1.5 * itemHeight));
        }
        return minFontSize;
    }

    /**
     * 改变值的时候回调通知
     */
    private void onPitchOnBack() {
        if (onPitchOnChangeListener != null) {
            String str = getPitchOn();
            if (lastValue == null || !str.equals(lastValue)) {
                onPitchOnChangeListener.onClick(str);
                lastValue = str;
            }
        }
    }

    /**
     * 设置数组
     *
     * @param strings
     */
    public void setList(final List strings) {
        if (strings == null || strings.size() <= 0) {
            return;
        }
        if (strings.size() < 9) {
            isLoop = false;
        } else {
            isLoop = true;
        }
        post(new Runnable() {
            @Override
            public void run() {
                itemHeight = getHeight() / 5;
                itemEntities = new ArrayList<>();
                for (int i = 0; i < strings.size(); i++) {
                    ItemEntity itemEntity = new ItemEntity();
                    itemEntity.setValue(strings.get(i));
                    itemEntity.setY(itemHeight * i);
                    itemEntities.add(itemEntity);
                }
                isSetList = true;
                if (!TextUtils.isEmpty(defaultValue)) {
                    //必须放在isSetList=true;后面,不然就没意义了
                    setPitchOn(defaultValue);
                }
                invalidate();
            }
        });
    }

    /**
     * 设置是否循环,如果小于9条记录,直接默认不给循环,必须在setList()之后调用,因为setList会有一个自动设置是否循环的动作
     *
     * @param bln
     */
    private void setIsLoop(boolean bln) {
        isLoop = bln;
        if (itemEntities.size() < 9) {
            isLoop = false;
        }
    }

    /**
     * 设置文字颜色
     *
     * @param normal 未选中颜色
     * @param press  选中颜色
     */
    public void setFontColor(int normal, int press) {
        normalFontColor = normal;
        pressFontColor = press;
    }


    /**
     * 根据高度设置最大最小字体的大小,范围是20-80
     *
     * @param minPercent
     * @param maxPercent
     */
    public void setFontSize(int minPercent, int maxPercent) {
        if (minPercent < 20) {
            minPercent = 20;
        }
        if (maxPercent < 20) {
            maxPercent = 20;
        }
        if (minPercent > 80) {
            minPercent = 80;
        }
        if (maxPercent > 80) {
            maxPercent = 80;
        }
        minFontSizePercent = minPercent;
        maxFontSizePercent = maxPercent;
        invalidate();
    }

    /**
     * 设置改变监听
     *
     * @param onStringListener
     */
    public void setOnPitchOnChangeListener(OnStringListener onStringListener) {
        this.onPitchOnChangeListener = onStringListener;
    }

    /**
     * 返回选中的
     *
     * @return
     */
    public String getPitchOn() {
        if (itemEntities != null) {
            for (int i = 0; i < itemEntities.size(); i++) {
                if (itemEntities.get(i).getY() > 1.8 * itemHeight && itemEntities.get(i).getY() < 2.8 * itemHeight) {
                    return itemEntities.get(i).getValue();
                }
            }
        }
        return "";
    }

    /**
     * 返回当前的列表
     *
     * @return
     */
    public List getList() {
        List strings = new ArrayList<>();
        if (itemEntities == null) {
            return strings;
        }
        for (int i = 0; i < itemEntities.size(); i++) {
            strings.add(itemEntities.get(i).getValue());
        }
        return strings;
    }

    /**
     * 设置当前选中的内容
     *
     * @param str
     */
    public void setPitchOn(String str) {
        if (isSetList) {
            //列表已经初始化了
            if (itemEntities == null) {
                return;
            }
            for (int i = 0; i < itemEntities.size(); i++) {
                if (itemEntities.get(i).getValue().equals(str)) {
                    setPitchOn(i);
                    return;
                }
            }
        } else {
            //列表还没初始化
            defaultValue = str;
        }
    }

    /**
     * 设置当前选中第几项
     *
     * @param position
     */
    public void setPitchOn(int position) {
        if (itemEntities == null || itemHeight == 0) {
            return;
        }
        itemEntities.get(position).setY(itemHeight * 2);
        for (int i = position - 1; i >= 0; i--) {
            itemEntities.get(i).setY(itemEntities.get(i + 1).getY() - itemHeight);
        }
        for (int i = position + 1; i < itemEntities.size(); i++) {
            itemEntities.get(i).setY(itemEntities.get(i - 1).getY() + itemHeight);
        }
        deviationY(0);//防止可循环情况下出现空缺,执行一下偏移操作进行调整
        invalidate();
    }

    class ItemEntity {
        private String value;//需要显示的文本
        private float y;//当前的y坐标

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public float getY() {
            return y;
        }

        public void setY(float y) {
            this.y = y;
        }
    }

    public int getNormalFontColor() {
        return normalFontColor;
    }

    public int getPressFontColor() {
        return pressFontColor;
    }

    public float getMinFontSize() {
        return minFontSize;
    }

    public float getMaxFontSize() {
        return maxFontSize;
    }
}

控件布局layout_picker.xml:

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


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">

        <com.imxiaoyu.common.widget.PickerItemView
            android:id="@+id/piv_year"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/tv_year"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="年" />

        <com.imxiaoyu.common.widget.PickerItemView
            android:id="@+id/piv_month"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/tv_month"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="月" />

        <com.imxiaoyu.common.widget.PickerItemView
            android:id="@+id/piv_day"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/tv_day"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="日" />

        <com.imxiaoyu.common.widget.PickerItemView
            android:id="@+id/piv_hour"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/tv_hour"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="时" />

        <com.imxiaoyu.common.widget.PickerItemView
            android:id="@+id/piv_minute"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/tv_minute"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="分" />

        <com.imxiaoyu.common.widget.PickerItemView
            android:id="@+id/piv_second"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/tv_second"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="秒" />

        <com.imxiaoyu.common.widget.PickerItemView
            android:id="@+id/piv_millisecond"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/tv_millisecond"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="毫秒" />

    LinearLayout>
RelativeLayout>

 

控件源码:

package com.imxiaoyu.common.widget;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.imxiaoyu.common.R;
import com.imxiaoyu.common.impl.OnStringListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * 日期、时间选择控件
 * Created by 庞光渝 on 2017/2/18.
 */

public class PickerView extends RelativeLayout {

    /**
     * UI
     */
    private PickerItemView pivYear;
    private PickerItemView pivMonth;
    private PickerItemView pivDay;
    private PickerItemView pivHour;
    private PickerItemView pivMinute;
    private PickerItemView pivSecond;
    private PickerItemView pivMillisecond;
    private TextView tvYear;
    private TextView tvMonth;
    private TextView tvDay;
    private TextView tvHour;
    private TextView tvMinute;
    private TextView tvSecond;
    private TextView tvMillisecond;

    /**
     * 变量
     */
    private List years;
    private List months;
    private List days;
    private List hours;
    private List minutes;
    private List seconds;
    private List milliseconds;

    private int year;
    private int month;
    private int day;
    private int hour;
    private int minute;
    private int second;
    private int millisecond;
    private OnPickerViewListener onPickerViewChangeListener;

    public PickerView(Context context) {
        super(context);
        initView(context);
    }

    public PickerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public PickerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        // 加载布局
        LayoutInflater.from(context).inflate(R.layout.layout_picker, this);
        pivYear = (PickerItemView) findViewById(R.id.piv_year);
        pivMonth = (PickerItemView) findViewById(R.id.piv_month);
        pivDay = (PickerItemView) findViewById(R.id.piv_day);
        pivHour = (PickerItemView) findViewById(R.id.piv_hour);
        pivMinute = (PickerItemView) findViewById(R.id.piv_minute);
        pivSecond = (PickerItemView) findViewById(R.id.piv_second);
        pivMillisecond = (PickerItemView) findViewById(R.id.piv_millisecond);
        tvYear = (TextView) findViewById(R.id.tv_year);
        tvMonth = (TextView) findViewById(R.id.tv_month);
        tvDay = (TextView) findViewById(R.id.tv_day);
        tvHour = (TextView) findViewById(R.id.tv_hour);
        tvMinute = (TextView) findViewById(R.id.tv_minute);
        tvSecond = (TextView) findViewById(R.id.tv_second);
        tvMillisecond = (TextView) findViewById(R.id.tv_millisecond);
        initView();
    }

    /**
     * 部分机型在popupWindow中,如果没有show popupWindow的话高度是一直为0的
     * 所以需要重写一下popupWindow的show方法中重新调用一下initView进行初始化,否则会显示错误
     */
    public void initView() {
        initData();
        initPIV();
        initWidth();
    }

    /**
     * 动态的写一下各个item的宽度
     */
    private void initWidth() {
        post(new Runnable() {
            @Override
            public void run() {
                float size = (float) ((getHeight() / 5) * 0.65);
                LinearLayout.LayoutParams params1 = (LinearLayout.LayoutParams) pivYear.getLayoutParams();
                params1.width = (int) (size * 3);
                pivYear.setLayoutParams(params1);
                LinearLayout.LayoutParams params2 = (LinearLayout.LayoutParams) pivMonth.getLayoutParams();
                params2.width = (int) (size * 1.7);
                pivMonth.setLayoutParams(params2);
                pivDay.setLayoutParams(params2);
                pivHour.setLayoutParams(params2);
                pivMinute.setLayoutParams(params2);
                pivSecond.setLayoutParams(params2);
                LinearLayout.LayoutParams params3 = (LinearLayout.LayoutParams) pivMonth.getLayoutParams();
                params2.width = (int) (size * 2.4);
                pivMillisecond.setLayoutParams(params3);

                /**
                 * 设置中间分隔字体的大小
                 */
//                tvYear.setTextSize(size);
//                tvMonth.setTextSize(size);
//                tvDay.setTextSize(size);
//                tvHour.setTextSize(size);
//                tvMinute.setTextSize(size);
//                tvSecond.setTextSize(size);
//                tvMillisecond.setTextSize(size);
            }
        });
    }

    /**
     * 响应监听
     */
    private void onChange() {
        if (onPickerViewChangeListener != null) {
            onPickerViewChangeListener.onChange(PickerView.this);
        }
    }

    /**
     * 初始化修改监听
     */
    private void initOnChange() {
        pivYear.setOnPitchOnChangeListener(new OnStringListener() {
            @Override
            public void onClick(String str) {
                try {
                    year = Integer.parseInt(pivYear.getPitchOn());
                    updateDay(str, pivMonth.getPitchOn());
                    onChange();
                } catch (Exception e) {

                }
            }
        });
        pivMonth.setOnPitchOnChangeListener(new OnStringListener() {
            @Override
            public void onClick(String str) {
                try {
                    month = Integer.parseInt(pivMonth.getPitchOn());
                    updateDay(pivYear.getPitchOn(), str);
                    onChange();
                } catch (Exception e) {

                }
            }
        });
        pivDay.setOnPitchOnChangeListener(new OnStringListener() {
            @Override
            public void onClick(String str) {
                try {
                    day = Integer.parseInt(pivDay.getPitchOn());
                    onChange();
                } catch (Exception e) {

                }
            }
        });
        pivHour.setOnPitchOnChangeListener(new OnStringListener() {
            @Override
            public void onClick(String str) {
                try {
                    hour = Integer.parseInt(pivHour.getPitchOn());
                    onChange();
                } catch (Exception e) {

                }
            }
        });
        pivMinute.setOnPitchOnChangeListener(new OnStringListener() {
            @Override
            public void onClick(String str) {
                try {
                    minute = Integer.parseInt(pivMinute.getPitchOn());
                    onChange();
                } catch (Exception e) {

                }
            }
        });
        pivSecond.setOnPitchOnChangeListener(new OnStringListener() {
            @Override
            public void onClick(String str) {
                try {
                    second = Integer.parseInt(pivSecond.getPitchOn());
                    onChange();
                } catch (Exception e) {

                }
            }
        });
        pivMillisecond.setOnPitchOnChangeListener(new OnStringListener() {
            @Override
            public void onClick(String str) {
                try {
                    millisecond = Integer.parseInt(pivMillisecond.getPitchOn());
                    onChange();
                } catch (Exception e) {

                }
            }
        });
    }

    /**
     * 初始化每一个Item的初始值
     */
    private void initPIV() {
        //年
        years = new ArrayList<>();
        for (int i = 1970; i < 2101; i++) {
            years.add(i + "");
        }
        pivYear.setList(years);

        //月
        months = new ArrayList<>();
        for (int i = 1; i < 13; i++) {
            months.add(int2Str2(i));
        }
        pivMonth.setList(months);

        //日
        days = getDayNumber(years.get(0), months.get(0));
        pivDay.setList(days);

        //时
        hours = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            hours.add(int2Str2(i));
        }
        pivHour.setList(hours);

        //分
        minutes = new ArrayList<>();
        for (int i = 0; i < 60; i++) {
            minutes.add(int2Str2(i));
        }
        pivMinute.setList(minutes);

        //秒
        seconds = new ArrayList<>();
        for (int i = 0; i < 60; i++) {
            seconds.add(int2Str2(i));
        }
        pivSecond.setList(seconds);

        //毫秒
        milliseconds = new ArrayList<>();
        for (int i = 0; i < 1000; i += 50) {
            milliseconds.add(int2Str2(i));
        }
        pivMillisecond.setList(milliseconds);

        //设置监听
        initOnChange();
    }

    /**
     * 动态更新日期天数
     *
     * @param year
     * @param month
     */
    public void updateDay(String year, String month) {
        try {
            List strings = getDayNumber(year, month);
            if (strings.size() != pivDay.getList().size()) {
                pivDay.setList(strings);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取一个月的天数
     */
    private List getDayNumber(String year, String monthStr) {
        int num = 30;
        try {
            int month = Integer.parseInt(monthStr);
            if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
                num = 31;
            }
            if (month == 2) {
                if (getLeapYear(year)) {
                    num = 29;
                } else {
                    num = 28;
                }
            }
        } catch (Exception e) {
            num = 31;
        }

        List strs = new ArrayList<>();
        for (int i = 1; i <= num; i++) {
            strs.add(int2Str2(i));
        }
        return strs;
    }

    /**
     * 设置初始值
     */
    private void initData() {
        Calendar now = Calendar.getInstance();
        year = now.get(Calendar.YEAR);
        month = now.get(Calendar.MONTH) + 1;
        day = now.get(Calendar.DAY_OF_MONTH);
        hour = now.get(Calendar.HOUR);
        minute = now.get(Calendar.MINUTE);
        second = now.get(Calendar.SECOND);
        millisecond = (int) (now.get(Calendar.MILLISECOND) % 1000);
        //毫秒的最小单位是50,所以转换一下
        millisecond = (millisecond / 50) * 50;
        update();
    }

    /**
     * 更新
     */
    private void update() {
        //设置初始值
        pivYear.setPitchOn(year + "");
        pivMonth.setPitchOn(int2Str2(month));
        pivDay.setPitchOn(int2Str2(day));
        pivHour.setPitchOn(int2Str2(hour));
        pivMinute.setPitchOn(int2Str2(minute));
        pivSecond.setPitchOn(int2Str2(second));
        pivMillisecond.setPitchOn(int2Str3(millisecond));
    }

    /**
     * 设置修改监听
     *
     * @param onPickerViewChangeListener
     */
    public void setOnPickerViewChangeListener(OnPickerViewListener onPickerViewChangeListener) {
        this.onPickerViewChangeListener = onPickerViewChangeListener;
    }

    /**
     * 根据需要,传入单位文本,如果为null或者空字符则表示不需要该项,
     * 如:只传时、分,则整个控件只有选择小时和分钟
     *
     * @param year
     * @param month
     * @param day
     * @param hour
     * @param minute
     * @param second
     * @param millisecond
     */
    public void setNameFormat(String year, String month, String day, String hour, String minute, String second, String millisecond) {
        //年
        if (TextUtils.isEmpty(year)) {
            tvYear.setVisibility(GONE);
            pivYear.setVisibility(GONE);
        } else {
            tvYear.setText(year);
            tvYear.setVisibility(VISIBLE);
            pivYear.setVisibility(VISIBLE);
        }

        //月
        if (TextUtils.isEmpty(month)) {
            tvMonth.setVisibility(GONE);
            pivMonth.setVisibility(GONE);
        } else {
            tvMonth.setText(month);
            tvMonth.setVisibility(VISIBLE);
            pivMonth.setVisibility(VISIBLE);
        }

        //日
        if (TextUtils.isEmpty(day)) {
            tvDay.setVisibility(GONE);
            pivDay.setVisibility(GONE);
        } else {
            tvDay.setText(day);
            tvDay.setVisibility(VISIBLE);
            pivDay.setVisibility(VISIBLE);
        }

        //时
        if (TextUtils.isEmpty(hour)) {
            tvHour.setVisibility(GONE);
            pivHour.setVisibility(GONE);
        } else {
            tvHour.setText(hour);
            tvHour.setVisibility(VISIBLE);
            pivHour.setVisibility(VISIBLE);
        }

        //分
        if (TextUtils.isEmpty(minute)) {
            tvMinute.setVisibility(GONE);
            pivMinute.setVisibility(GONE);
        } else {
            tvMinute.setText(minute);
            tvMinute.setVisibility(VISIBLE);
            pivMinute.setVisibility(VISIBLE);
        }

        //秒
        if (TextUtils.isEmpty(second)) {
            tvSecond.setVisibility(GONE);
            pivSecond.setVisibility(GONE);
        } else {
            tvSecond.setText(second);
            tvSecond.setVisibility(VISIBLE);
            pivSecond.setVisibility(VISIBLE);
        }

        //毫秒
        if (TextUtils.isEmpty(millisecond)) {
            tvMillisecond.setVisibility(GONE);
            pivMillisecond.setVisibility(GONE);
        } else {
            tvMillisecond.setText(millisecond);
            tvMillisecond.setVisibility(VISIBLE);
            pivMillisecond.setVisibility(VISIBLE);
        }
    }

    /**
     * 根据高度设置最大最小字体的大小,范围是20-80
     *
     * @param minPercent
     * @param maxPercent
     */
    public void setFontSize(int minPercent, int maxPercent) {
        pivYear.setFontSize(minPercent, maxPercent);
        pivMonth.setFontSize(minPercent, maxPercent);
        pivDay.setFontSize(minPercent, maxPercent);
        pivHour.setFontSize(minPercent, maxPercent);
        pivMinute.setFontSize(minPercent, maxPercent);
        pivSecond.setFontSize(minPercent, maxPercent);
        pivMillisecond.setFontSize(minPercent, maxPercent);
    }

    /**
     * 设置文字颜色
     *
     * @param normal 未选中颜色
     * @param press  选中颜色
     */
    public void setFontColor(int normal, int press) {
        pivYear.setFontColor(normal, press);
        pivMonth.setFontColor(normal, press);
        pivDay.setFontColor(normal, press);
        pivHour.setFontColor(normal, press);
        pivMinute.setFontColor(normal, press);
        pivSecond.setFontColor(normal, press);
        pivMillisecond.setFontColor(normal, press);
    }

    /**
     * 设置分隔字体的样式
     *
     * @param fontSize  字体大小,空为默认
     * @param fontColor 颜色大小,空位默认
     */
    public void setSeparateTvStyle(Integer fontSize, Integer fontColor) {
        if (fontSize != null) {
            tvYear.setTextSize(fontSize);
            tvMonth.setTextSize(fontSize);
            tvDay.setTextSize(fontSize);
            tvHour.setTextSize(fontSize);
            tvMinute.setTextSize(fontSize);
            tvSecond.setTextSize(fontSize);
            tvMillisecond.setTextSize(fontSize);
        }
        if (fontColor != null) {
            tvYear.setTextColor(fontColor);
            tvMonth.setTextColor(fontColor);
            tvDay.setTextColor(fontColor);
            tvHour.setTextColor(fontColor);
            tvMinute.setTextColor(fontColor);
            tvSecond.setTextColor(fontColor);
            tvMillisecond.setTextColor(fontColor);
        }
    }

    /**
     * 计算是否是闰年
     * (能被4整除且不是整百年份的是闰年,能被4整除且是整百的只有能被400整除的才是闰年,即2000是闰年,但1900不是
     *
     * @param year
     * @return
     */
    private boolean getLeapYear(String year) {
        int num = Integer.parseInt(year);
        if (num % 4 == 0) {
            if (num % 100 == 0 && num % 400 != 0) {
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 1-->01
     */
    public static String int2Str2(int num) {
        String str = "";
        if (num < 10) {
            str = "0" + num;
        } else {
            str = "" + num;
        }
        return str;
    }

    /**
     * 1-->001
     */
    public static String int2Str3(int num) {
        String str = "";
        if (num < 10) {
            str = "00" + num;
        } else {
            if (num < 100) {
                str = "0" + num;
            } else {
                str = "" + num;
            }
        }
        return str;
    }

    public static interface OnPickerViewListener {
        public void onChange(PickerView pickerView);
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
        update();
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
        update();
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
        update();
    }

    public int getHour() {
        return hour;
    }

    public void setHour(int hour) {
        this.hour = hour;
        update();
    }

    public int getMinute() {
        return minute;
    }

    public void setMinute(int minute) {
        this.minute = minute;
        update();
    }

    public int getSecond() {
        return second;
    }

    public void setSecond(int second) {
        this.second = second;
        update();
    }

    public int getMillisecond() {
        return millisecond;
    }

    public void setMillisecond(int millisecond) {
        this.millisecond = millisecond;
        update();
    }
}

Item的回调接口:

package com.imxiaoyu.common.impl;

/**
 * 回调一个字符串
 * Created by 她叫我小渝 on 2016/11/1.
 */

public interface OnStringListener {
    void onClick(String str);
}

http://doutugongchang.com/

你可能感兴趣的:(技术)