[83→100]Android好用的日历控件——MaterialCalendarView

需求

最近项目中需要用到日历控件,需求如下

  1. 同时支持周模式和月模式
  2. 支持边界设置,有些地方要求只显示当前周和下一周
  3. 支持日期禁用,某些特定的日期不允许点击
  4. 支持自定义的选中日期的样式
  5. 左右滑动自动切换周、月,同时自动选中同等位置的日期。

找来找去,最后发现GitHub的material-calendarview这个项目最贴近以上需求,稍作修改就能用了。

material-calendarview

项目开源地址:
https://github.com/prolificinteractive/material-calendarview

集成清单

  1. 添加compile 'com.prolificinteractive:material-calendarview:1.4.0'
  2. 添加日历控件到布局中
<com.prolificinteractive.materialcalendarview.MaterialCalendarView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/calendarView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:mcv_showOtherDates="all"
    app:mcv_selectionColor="#00F"
    />

功能展示

material-calendarview项目提供9个Sample来展示其功能用法

一、对照组:OldCalendarViewActivity

<CalendarView
        android:id="@+id/calendarView"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        />

采用系统控件CalendarView,实现一个点击显示日期的功能,可惜在低版本Android手机上没有material的样式,颜值很低,不能用。

二、基本用法:BasicActivity

  1. 绑定控件
@Bind(R.id.calendarView)
MaterialCalendarView widget;
  1. OnDateSelectedListener:用来监听选中日期的变化,
/**
 * The callback used to indicate a date has been selected or deselected
 */
public interface OnDateSelectedListener {

    /**
     * Called when a user clicks on a day.
     * There is no logic to prevent multiple calls for the same date and state.
     *
     * @param widget   the view associated with this listener
     * @param date     the date that was selected or unselected
     * @param selected true if the day is now selected, false otherwise
     */
    void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected);
}
  1. OnMonthChangedListener:用来接听页面滑动的变化,这个有点名不副实,因为在周模式的时候,滑动页面是按周来变化的
/**
 * The callback used to indicate the user changes the displayed month
 */
public interface OnMonthChangedListener {

    /**
     * Called upon change of the selected day
     *
     * @param widget the view associated with this listener
     * @param date   the month picked, as the first day of the month
     */
    void onMonthChanged(MaterialCalendarView widget, CalendarDay date);
}
  1. getSelectedDate():获取被选中的日期。
private String getSelectedDatesString() {
    CalendarDay date = widget.getSelectedDate();
    if (date == null) {
        return "No Selection";
    }
    return FORMATTER.format(date.getDate());
}

三、修饰选中日期:BasicActivityDecorated

  1. 设置日期范围
widget.setShowOtherDates(MaterialCalendarView.SHOW_ALL);
Calendar instance = Calendar.getInstance();
widget.setSelectedDate(instance.getTime());
Calendar instance1 = Calendar.getInstance();
instance1.set(instance1.get(Calendar.YEAR), Calendar.JANUARY, 1);
Calendar instance2 = Calendar.getInstance();
instance2.set(instance2.get(Calendar.YEAR), Calendar.DECEMBER, 31);
widget.state().edit()
        .setMinimumDate(instance1.getTime())
        .setMaximumDate(instance2.getTime())
        .commit();
  1. 增加日期修饰
widget.addDecorators(
        new MySelectorDecorator(this),
        new HighlightWeekendsDecorator(),
        oneDayDecorator
);

案例提供了三种修饰:

  1. 对选中日期增加指定背景图层
public class MySelectorDecorator implements DayViewDecorator {

    private final Drawable drawable;

    public MySelectorDecorator(Activity context) {
        drawable = context.getResources().getDrawable(R.drawable.my_selector);
    }

    @Override
    public boolean shouldDecorate(CalendarDay day) {
        return true;
    }

    @Override
    public void decorate(DayViewFacade view) {
        view.setSelectionDrawable(drawable);
    }
}
  1. 对周末增加指定背景图层
/**
 * Highlight Saturdays and Sundays with a background
 */
public class HighlightWeekendsDecorator implements DayViewDecorator {

    private final Calendar calendar = Calendar.getInstance();
    private final Drawable highlightDrawable;
    private static final int color = Color.parseColor("#228BC34A");

    public HighlightWeekendsDecorator() {
        highlightDrawable = new ColorDrawable(color);
    }

    @Override
    public boolean shouldDecorate(CalendarDay day) {
        day.copyTo(calendar);
        int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
        return weekDay == Calendar.SATURDAY || weekDay == Calendar.SUNDAY;
    }

    @Override
    public void decorate(DayViewFacade view) {
        view.setBackgroundDrawable(highlightDrawable);
    }
}
  1. 对选中日期增加指定修饰
/**
 * Decorate a day by making the text big and bold
 */
public class OneDayDecorator implements DayViewDecorator {

    private CalendarDay date;

    public OneDayDecorator() {
        date = CalendarDay.today();
    }

    @Override
    public boolean shouldDecorate(CalendarDay day) {
        return date != null && day.equals(date);
    }

    @Override
    public void decorate(DayViewFacade view) {
        view.addSpan(new StyleSpan(Typeface.BOLD));
        view.addSpan(new RelativeSizeSpan(3.0f));
    }

    /**
     * We're changing the internals, so make sure to call {@linkplain MaterialCalendarView#invalidateDecorators()}
     */
    public void setDate(Date date) {
        this.date = CalendarDay.from(date);
    }
}
  1. 对特定日期增加红点修饰
/**
 * Decorate several days with a dot
 */
public class EventDecorator implements DayViewDecorator {

    private int color;
    private HashSet<CalendarDay> dates;

    public EventDecorator(int color, Collection<CalendarDay> dates) {
        this.color = color;
        this.dates = new HashSet<>(dates);
    }

    @Override
    public boolean shouldDecorate(CalendarDay day) {
        return dates.contains(day);
    }

    @Override
    public void decorate(DayViewFacade view) {
        view.addSpan(new DotSpan(5, color));
    }
}

四、模式切换:SwappableBasicActivityDecorated

切换周模式、月模式

@OnClick(R.id.button_weeks)
public void onSetWeekMode() {
    widget.state().edit()
            .setCalendarDisplayMode(CalendarMode.WEEKS)
            .commit();
}

@OnClick(R.id.button_months)
public void onSetMonthMode() {
    widget.state().edit()
            .setCalendarDisplayMode(CalendarMode.MONTHS)
            .commit();
}

五、日期禁用:DisableDaysActivity

核心代码是:

DayViewFacade view
view.setDaysDisabled(true);

这个作者非常喜欢用装饰模式。所以对DayViewFacade的修饰可以无穷的累加。只要集成DayViewDecorator就可以。

/**
 * Decorate Day views with drawables and text manipulation
 */
public interface DayViewDecorator {

    /**
     * Determine if a specific day should be decorated
     *
     * @param day {@linkplain CalendarDay} to possibly decorate
     * @return true if this decorator should be applied to the provided day
     */
    boolean shouldDecorate(CalendarDay day);

    /**
     * Set decoration options onto a facade to be applied to all relevant days
     *
     * @param view View to decorate
     */
    void decorate(DayViewFacade view);

}

六、透过xml自定义控件:CustomizeXmlActivity

<com.prolificinteractive.materialcalendarview.MaterialCalendarView
        android:id="@+id/calendarView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:mcv_showOtherDates="all"
        app:mcv_arrowColor="?attr/colorPrimary"
        app:mcv_leftArrowMask="@drawable/ic_navigation_arrow_back"
        app:mcv_rightArrowMask="@drawable/ic_navigation_arrow_forward"
        app:mcv_selectionColor="?attr/colorPrimary"
        app:mcv_headerTextAppearance="?android:attr/textAppearanceMedium"
        app:mcv_dateTextAppearance="@style/CustomDayTextAppearance"
        app:mcv_weekDayTextAppearance="?android:attr/textAppearanceMedium"
        app:mcv_weekDayLabels="@array/custom_weekdays"
        app:mcv_monthLabels="@array/custom_months"
        app:mcv_tileSize="36dp"
        app:mcv_firstDayOfWeek="thursday"
        app:mcv_calendarMode="week"
        />

xml中能设置的属性很多,常用的如下:

  • mcv_showOtherDates:日期范围
  • mcv_firstDayOfWeek:一周的第一天
  • mcv_calendarMode:日历模式

七、透过java自定义控件:CustomizeCodeActivity

效果和xml是一致的。

widget.setShowOtherDates(MaterialCalendarView.SHOW_ALL);
widget.setArrowColor(getResources().getColor(R.color.sample_primary));
widget.setLeftArrowMask(getResources().getDrawable(R.drawable.ic_navigation_arrow_back));
widget.setRightArrowMask(getResources().getDrawable(R.drawable.ic_navigation_arrow_forward));
widget.setSelectionColor(getResources().getColor(R.color.sample_primary));
widget.setHeaderTextAppearance(R.style.TextAppearance_AppCompat_Medium);
widget.setWeekDayTextAppearance(R.style.TextAppearance_AppCompat_Medium);
widget.setDateTextAppearance(R.style.CustomDayTextAppearance);
widget.setTitleFormatter(new MonthArrayTitleFormatter(getResources().getTextArray(R.array.custom_months)));
widget.setWeekDayFormatter(new ArrayWeekDayFormatter(getResources().getTextArray(R.array.custom_weekdays)));
widget.setTileSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 36, getResources().getDisplayMetrics()));

CalendarDay today = CalendarDay.from(2016, 5, 2);
widget.setCurrentDate(today);
widget.setSelectedDate(today);

widget.state().edit()
        .setFirstDayOfWeek(Calendar.WEDNESDAY)
        .setMinimumDate(CalendarDay.from(2016, 4, 3))
        .setMaximumDate(CalendarDay.from(2016, 5, 12))
        .setCalendarDisplayMode(CalendarMode.WEEKS)
        .commit();

八、完整的设置展示DynamicSettersActivity

九、在Dialog中显示日历:DialogsActivity

拓展:滑屏时自动选中日期

widget.setOnDateChangedListener(new OnDateSelectedListener() {
    @Override
    public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
        if (selected && date != null){
            dayOfWeek = date.getCalendar().get(Calendar.DAY_OF_WEEK);
            dayofMonth = date.getCalendar().get(Calendar.DAY_OF_MONTH);
        }
        Log.d(TAG, "date = " + date);
        Log.d(TAG, "dayOfWeek = " + dayOfWeek);
        Log.d(TAG, "dayofMonth = " + dayofMonth);
    }
});

widget.setOnMonthChangedListener(new OnMonthChangedListener() {
    @Override
    public void onMonthChanged(final MaterialCalendarView widget, CalendarDay date) {
        Calendar c = date.getCalendar();
        Log.d(TAG, "date = " + date);
        Calendar now = c;
        if (widget.state().calendarMode == CalendarMode.WEEKS){
            now.set(Calendar.DAY_OF_WEEK, c.get(Calendar.DAY_OF_WEEK) + dayOfWeek - 1);
        }
        else{
            now.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + dayofMonth - 1);
        }
        CalendarDay nowDate = CalendarDay.from(now);
        Log.d(TAG, "nowDate = " + nowDate);
        widget.setSelectedDate(nowDate);
    }
});

Calendar instance = Calendar.getInstance();
widget.setSelectedDate(instance.getTime());

Panda
2016-07-19

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,332评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,508评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,812评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,607评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,728评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,919评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,071评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,802评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,256评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,576评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,712评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,389评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,032评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,026评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,473评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,606评论 2 350

推荐阅读更多精彩内容