最近公司项目里有这样一个需求,点击弹出日期选择器,就是我们经常说的日历控件,讲道理来说我们可以通过Dialog来实现,也可以写一个对话框样式的Activity。而我选择的就是用Dialog来实现。但是思路虽好,在实现过程中遇到了一个坑点,然后又亲手填平,没毛病,就是填平的。。。。
首先我去GitHub上搜索日历控件开源库,把地址粘出来(https://github.com/SundeepK/CompactCalendarView)主要实现思路为点击弹出对话框,把日历控件单独放到一个layout里,然后加载到Dialog上。就这么简单。下面 老司机要开车了....
直接上代码吧 简单粗暴。
<com.github.sundeepk.compactcalendarview.CompactCalendarView
android:id="@+id/basecalendarview"
android:layout_width="match_parent"
android:layout_height="250dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
app:compactCalendarBackgroundColor="#ffe95451"
app:compactCalendarCurrentDayBackgroundColor="#B71C1C"
app:compactCalendarCurrentSelectedDayBackgroundColor="#E57373"
app:compactCalendarMultiEventIndicatorColor="#fff"
app:compactCalendarTargetHeight="250dp"
app:compactCalendarTextColor="#fff"
app:compactCalendarTextSize="12sp"
></com.github.sundeepk.compactcalendarview.CompactCalendarView>
这是日历的布局文件,讲道理来说我们只需要通过AlertDialog当中的setView()方法来把这个布局加载进去
mInflate = LayoutInflater.from(this).inflate(R.layout.dialogview, null);把布局转化为View对象。
mBuilder.setView(mInflate)实现对话框的代码就不粘了,大家基本上都会。
代码写到这楼主当然是按耐不住自己激动地心情跑了一把啊,可是。。。还算顺利,界面出来了
虽然界面简陋但至少证明写的没问题,然而。。。 异常来了 当我第二次点击显示按钮的时候,崩沙卡拉卡。直接报异常
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
显而易见他说我没有移除View。可是弹个对话框消失了销毁个毛线的View啊,楼主也是头次碰到。不过根据经验来看,开源日历控件里面包含了ViewPager,这就让我想到在我关闭dailog
时可以尝试销毁父布局 具体代码如下
private void destoryView(View view) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) { parent.removeAllViews(); } }在对话框的确认和取消按钮的方法里调用
destoryView(mInflate);并且设置dialog的setCancelable(false)属性来设置对话框点击外面和按返回键不会消失,至此,bug解决了,遇到这个异常还是自己的基本功不够扎实,
对于View的绘制源码需要进一步的钻研。
车停了 该下车的下车啊。。