如何在CalendarView中获取当前月份?

时间:2015-12-01 12:39:59

标签: android

我使用CalendarView类在我的应用中插入日历。我已经这样做了:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<CalendarView
    android:id="@+id/calendar_userCalendar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:clickable="true" />

</RelativeLayout>

有了这个,我可以看到这样的日历:

enter image description here

所有月份都可见! 我尝试按编程方式按当前月份进行过滤:

calendar = (CalendarView) inflatedLayout.findViewById(R.id.calendar_userCalendar);

Calendar cal = Calendar.getInstance();
int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.setMaxDate(daysInMonth);

但它仍然显示所有月份...如何设置日历以仅显示当月和过滤本月的事件?

1 个答案:

答案 0 :(得分:1)

您必须获取月份的开始和结束日期,然后将其设置为日历对象以显示

public Pair<Date, Date> getDateRange() {
    Date begining, end;

    {
        Calendar calendar = getCalendarForNow();
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        setTimeToBeginningOfDay(calendar);
        begining = calendar.getTime();
    }

    {
        Calendar calendar = getCalendarForNow();
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        setTimeToEndofDay(calendar);
        end = calendar.getTime();
    }

    return Pair.create(begining, end);
}

private static Calendar getCalendarForNow() {
    Calendar calendar = GregorianCalendar.getInstance();
    calendar.setTime(new Date());
    return calendar;
}

private static void setTimeToBeginningOfDay(Calendar calendar) {
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
}

private static void setTimeToEndofDay(Calendar calendar) {
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
}

您可以使用上面的代码获取月份的开始和结束日期]然后您可以设置要预览的月份的开始和结束日期