5

In android , i am using an default CalendarView. I have set the background to light gray color. But can i change the color of month view of calendar view?

Ryan
  • 672
  • 8
  • 15
Sandeep Dhull
  • 1,638
  • 2
  • 18
  • 30
  • I have gone through the source code of the CalendarView , and i found out that there an texview mMonthTextView.. but it is not accessible outside.. so there's no way to set the text color of that textview.. – Sandeep Dhull Nov 16 '12 at 06:56
  • wjat about styles? might be able to set it in the manifest – Moog Nov 29 '12 at 08:16

2 Answers2

12

As you've found out, the TextView is private, and there does not seem to be any methods for accessing it.

Although I wouldn't recommend it, you can accomplish this using the java.lang.reflect package:

    try
    {
        CalendarView cv = (CalendarView) this.findViewById(R.id.calendarView1);
        Class<?> cvClass = cv.getClass();
        Field field = cvClass.getDeclaredField("mMonthName");
        field.setAccessible(true);

        try
        {
            TextView tv = (TextView) field.get(cv);
            tv.setTextColor(Color.RED);
        } 
        catch (IllegalArgumentException e)
        {
            e.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }
    }
    catch (NoSuchFieldException e)
    {
        e.printStackTrace();
    }
Ryan
  • 672
  • 8
  • 15
  • @Ryan I want to change the name of the month that appears at the top and I can do it using this way. However, the date changes back to normal whenever I scroll the calendarview up or down. any hints ? – tony9099 Sep 11 '14 at 06:59
  • @tony9099 No simple way of doing that comes to mind, unfortunately. You can see the code for CalendarView [here at grepcode.com](http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/widget/CalendarView.java). `setMonthDisplayed` is the method called to update the TextView. – Ryan Sep 13 '14 at 16:57
  • @Tim see my answer for working solution for Android 5.x – 1615903 Apr 15 '15 at 10:20
6

On Android 5.x I have used the following solution (it works on older versions too):

CalendarView cv = (CalendarView) this.findViewById(R.id.calendarView1);
ViewGroup vg = (ViewGroup) cv.getChildAt(0);
View child = vg.getChildAt(0);

if(child instanceof TextView) {
    ((TextView)child).setTextColor(getResources().getColor(R.color.black));
}

The layout for calendarview can be found here, and based on that the month name TextView is the first child in the layout.

1615903
  • 32,635
  • 12
  • 70
  • 99