2015-12-01 74 views
-1

我正在使用CalendarView類在我的應用中插入日曆。我已經做了這樣的:如何在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

你必須得到啓動和月份的結束日期,然後將其設置爲你的日曆對象,以顯示

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); 
} 

您可以使用上面的代碼獲得該月的起始和結束日期]和那麼你可以設置月份的起始和結束日期來預覽

+0

這樣做的竅門!謝謝! – Sonhja

相關問題