javaandroidandroid-calendarcalendarview

How to know which month and year is currently visible in CalendarView?


I am developing an app that is based on MaterialCalendarView (prolificinteractive) I am decorating days with drawables etc. I want to know which month and year is currently visible to the user so that I can only apply the decorater for the current visible month and not all the months as it will slow the app for no reason. Note : I am not talking about the current selected date.


Solution

  • There's a OnMonthChangedListener already but it doesn't even have a month parameter! If you don't mind reflection, you can do this:

    calview.setOnMonthChangedListener((widget, date) -> {
        try {
            Field currentMonthField = MaterialCalendarView.class.getDeclaredField("currentMonth");
            currentMonthField.setAccessible(true);
            int currentMonth = ((CalendarDay) currentMonthField.get(widget)).getMonth();
            // Do something, currentMonth is between 1 and 12.
    
        } catch (NoSuchFieldException | IllegalAccessException e) {
            // Failed to get field value, maybe library was changed.
        }
    });
    

    Or better yet, open and issue or make a pull request to either make that field public on pass its value when the listener is called.