无论在Dialog、PopupWindow等View中嵌套CalendarView的时候,都会出现CalendarView显示卡顿的问题,或者显示的日历只有星期,具体的日期无法看到的问题,更甚至出现ANR的问题,而且查看Location也可以看到以下相关的日志:
D/dalvikvm: GC_FOR_ALLOC freed 2649K (61944), 27% free 7714K/10480K, paused 40ms, total 40ms
D/dalvikvm: GC_FOR_ALLOC freed 3115K (84688), 30% free 7669K/10904K, paused 40ms, total 40ms
D/dalvikvm: GC_FOR_ALLOC freed 3072K (83720), 30% free 7669K/10904K, paused 40ms, total 40ms
D/dalvikvm: GC_FOR_ALLOC freed 3071K (83706), 30% free 7669K/10904K, paused 45ms, total 45ms
D/dalvikvm: GC_FOR_ALLOC freed 3071K (83706), 30% free 7669K/10904K, paused 41ms, total 41ms
D/dalvikvm: GC_FOR_ALLOC freed 3071K (83707), 30% free 7669K/10904K, paused 43ms, total 43ms
D/dalvikvm: GC_FOR_ALLOC freed 3071K (83709), 30% free 7669K/10904K, paused 40ms, total 40ms
D/dalvikvm: GC_FOR_ALLOC freed 3072K (83710), 30% free 7669K/10904K, paused 39ms, total 39ms
D/dalvikvm: GC_FOR_ALLOC freed 3071K (83708), 30% free 7669K/10904K, paused 42ms, total 42ms
一般向Dialog或PopupWindow添加CalendarView,大部分人写的代码都是诸如:
// 通过java代码动态添加CalendarView
...
CalendarView calendar = new CalendarView(this);
PopupWindow popupWindow = new PopupWindow(calendar, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
...
或者:
// 通过layout文件inflate
...
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_calendar, null);
builder.setView(v);
builder.create().show();
...
其中dialog_calendar布局如下:
<CalendarView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
添加CalendarView的方法是通过inflate对应的layout文件来添加,而且layout文件中CalendarView不能作为根布局,所以完整的代码大概这样子:
// 通过inflate来添加CalendarView
View calendar = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_calendar, null, false);
popupWindow = new PopupWindow(calendar, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
其中,layout_calendar如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CalendarView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/calendarView"
android:layout_width="match_parent"
android:layout_height="400dp"
android:clickable="true"
android:showWeekNumber="false" />
LinearLayout>