前言
今天要讲的主角就是LayoutInflater,相信大家都用过吧。在动态地加载布局时,经常可以看见它的身影。比如说在Fragment的onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
方法里,就需要我们返回Fragment的View。这时就可以用inflater.inflate(R.layout.fragment_view, container, false)
来加载视图。那么下面就来探究一下LayoutInflater的真面目吧。
from(Context context)
首先我们在使用LayoutInflater时,通常用LayoutInflater.from(Context context)
这个方法来得到其对象:
1 | /** |
我们可以看到原来from(Context context)
这个方法只不过把context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
进行简单地封装了一下,方便开发者调用。相信大家都看得懂。
inflate(…)
在得到了LayoutInflater的对象之后,我们就要使用它的inflate()方法了。
可以看到inflate()有四个重载的方法。我们先来看看前三个的源码:
1 | public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { |
看到这里,我们都明白了,前三个inflate()方法到最后都是调用了inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
这个方法。原来第四个inflate()方法才是“幕后黑手”。那让我们来揭开它的黑纱吧:
1 | public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) { |
这段代码有点长,不过别担心,我们慢慢来看。首先把传入的parser
进行解析,创建视图。其中我们可以注意到在Android的源码中是用Pull方式来解析xml得到视图的。接下来判断了传入的root
是否为null,如果root
不为null并且attachToRoot
为false的情况下,temp.setLayoutParams(params);
。也就是说把创建出来的视图的LayoutParams设置为params。那么params又是从哪里来的呢?可以在上面一行可以找到params = root.generateLayoutParams(attrs);
我们来看看源码:
1 | public LayoutParams generateLayoutParams(AttributeSet attrs) { |
也就是说,在root
不为null并且attachToRoot
为false的情况下,把root
的LayoutParams设置给了新创建出来的View。
好了,再往下看,我们注意到了root
不为null并且attachToRoot
为true的情况。调用了root.addView(temp, params);
,在其内部就是将temp添加进了root中。即最后得到的View的父布局就是root。
最后一个情况就是(root == null || !attachToRoot)
时,直接返回了temp。
总结
到这里,关于LayoutInflater的讲解就差不多了,最后我们就来总结一下:
- 在root!=null并且attachToRoot为false:将root的LayoutParams设置给了View。
- 在root!=null并且attachToRoot为true:把root作为View的父布局。
- 在root==null时:直接返回View,无视attachToRoot的状态。
今天就到这,如有问题可以在下面留言。
~have a nice day~