Android LayoutInflater 方法总结

234 阅读2分钟

一般在activity中通过setContentView()将界面显示出来,但是如果在非activity中如何对控件布局设置操作了,这需LayoutInflater动态加载。在Android开发中相信很多人都会经常在fragment设置布局或者相关Recycleview适配器里面 看到以下这几个常用设置方法: 

inflater.inflate(R.layout.layout_test,null);
inflater.inflate(R.layout.layout_test, root,false);
inflater.inflate(R.layout.layout_test, root,true);

底层参数方法说明如下:

  
  public View inflate(int resource, ViewGroup root) {
        return inflate(resource, root, root != null);
  }
  public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
  }

 结论:如果attachToRoot是true的话,那第一个参数的layout文件就会被填充并附加在第二个参数所指定的ViewGroup内,方法返回结合后的View,根元素是第二个参数ViewGroup;如果是false的话,第一个参数所指定的layout文件会被填充并作为View返回,这个View的根元素就是layout文件的根元素。不管是true还是false, 都需要ViewGroup的LayoutParams来正确的测量与放置layout文件所产生的View对象。

注意: inflate 方法与 findViewById 方法不同; inflater 是用来找 res/layout 下的 xml 布局文件,并且实例化; findViewById() 是找具体 xml 布局文件中的具体 widget 控件(如:Button、TextView 等)。

在网上一定会遇到一些不正确的建议。有些人会建议你如果将attachToRoot设置为false的话直接将根ViewGroup传入null。但是,如果有父元素的话,还是应该传入的。

如果可以传入ViewGroup作为根元素,那就传入它;
避免将null作为根ViewGroup传入;
当我们不负责将layout文件的View添加进ViewGroup时设置attachToRoot参数为false;

比如:

RecyclerView负责决定什么时候展示它的子View,这个不由我们决定。在任何我们不负责将View添加进ViewGroup的情况下都应该将attachToRoot设置为false。

当在Fragment的onCreateView()方法中填充并返回View时,要将attachToRoot设为false。如果传入true,会抛出IllegalStateException:因为指定的子View已经有父View了。你只需要负责指定在哪里将Fragment的View放进Activity里就可以了,而添加、移除或替换Fragment则是FragmentManager的事情。

不要在View已经被添加进ViewGroup时传入true;
自定义View时很适合attachToRoot设置为true。


参考博客:www.bignerdranch.com/blog/unders…