最近在项目中用到了自定义Dialog,以前也是经常用,只不过要么是用自带的dialog样式,要么也是很简单的布局,所以并没有重视修改dialog大小的坑。直到这次项目中产(keng)品(die)经(wan)理(yi)死了都说dialog大小别扭要求改,然后突然发现自己自定义的dialog的大小不能调整后整个人都惊呆了,因此打算深入源码看看解决这个问题。本文分析的源代码均来自Android API 24。
demo的自定义布局如下:

首先想着通过修改dialog的Window来进行修改,代码如下:


em.....emmmm???尼玛?这啥玩意儿??还是没变?再怎么4000的大小也不会是这么个小玩意儿把?郁闷之极....(我太仁慈大小给4000太小了?)


然而百思不得其解为什么必须要在show之后才能显示??按照正常逻辑不应该在show之前设置大小???

show方法中的代码居然不是我想象中的一两行代码,而是那么多!首先在上图中标注1处,因为我们是创建新的dialog,所以会执行dispatchOnCreate(null)这个方法。顾名思义,调用创建,这里面肯定大有文章,猜测是进行了Dialog的创建,我们跟进去查看具体源码。

跟进去后发现里面调用了onCreate()方法,在这里是不是有种似曾相识的感觉?怎么感觉和Activity差不多了呢?按捺住基动的内心我们跟进去继续看看。因为Dialog的onCreate()方法实现为空的,所以我们选择一个子类来进行查看,我们进入AlertDialog中查看:

我们发现调用了mAlet.installContent()方法,我们来看看这是什么东东。AlertController是一个AlertDialog的控制类,包括在创建AlertDialog时(代码如下):
AlertDialog mTextDialog = new AlertDialog.Builder(context).setTitle("温馨提示").setView(view) .create();
在这里使用的Builder模式中,setTitle之类的设置参数也是先将参数设置给AlertController.Param。具体在这里就暂时不管。
我们继续查看installContent()方法:

先设置dialog的contentView,然后调用setContentView()方法。是不是越来越熟悉这个套路!继续忍着压抑砰砰直跳的小内心,继续跟进去看看。

我们看到,在Dialog类中我们发现它最终调用了Window的setContentView()方法;而Window在Android中只有PhoneWindow这一个实现类。 接下来的工作就是和Activity中的步骤一模一样,因为都是调用Window的setContentView()方法;具体分析可看我记录的另一篇文章内容(传送门:http://www.jianshu.com/p/28bbb6778593)。
通过setContentView()方法后,创建了Dialog的decorView,并且将我们的自定义布局加入到decorView中。其中在这个过程中,mWindowAttributes的高度和宽度在mWindow.setContentView()中的installDecor()中的generateLayout()中被修改,在这里贴出修改部分的代码:



在上面图中的标注处调用了setLayout(int width,int height)方法,这里传入了自适应的常量方式。而在setLayout方法中首先获取window的LayoutParams,然后修改了宽高。因此在这里过后,Window的mWindowAttributes将会重新改变,因此导致了我们在show之前修改的mWindowAttributes值将被覆盖,因此失效!
接下来把debug模式下错误代码的参数贴出来看看:


可以看出就算之前设置参数,随后在show方法中也会被覆盖,因此在show之前设置参数无效。

至此我们就将设置Dialog的Window宽高没有效果的原因分析完毕。
网友评论