其他分享
首页 > 其他分享> > LayoutInflater.inflate()总结

LayoutInflater.inflate()总结

作者:互联网

1. 什么是LayoutInflater?

 一个布局的xml一般可以调用Activity的setContentView()加载布局,然后把它显示到屏幕上,其实它底层就是Android系统服务中的LayoutInflater(布局服务),用的Android内置的Pull解析器来解析布局。一般在Android动态加载布局或者添加控件用得较多。

​ LayoutInflater就是一个用于加载布局的系统服务,就是实例化与Layout XML文件对应的View对象,不能直接使用, 需要通过***getLayoutInflater***( )方法或***getSystemService***( )方法来获得与当前Context绑定的 LayoutInflater实例!

//获取LayoutInflater实例的三种方法:
LayoutInflater inflater1 = LayoutInflater.from(this);
LayoutInflater inflater2 = getLayoutInflater();
LayoutInflater inflater3 = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

2. 什么是LayoutInflater.inflate() ?

public View inflate (int resource, ViewGroup root, boolean attachToRoot)

该方法的三个参数依次为:

①要加载的布局对应的资源id

②为该布局的外部再嵌套一层父布局,如果不需要的话,写null就可以了!

③是否为加载的布局文件的最外层套一层root布局,不设置该参数的话, 如果root不为null的话,则默认为true 如果root为null的话,attachToRoot就没有作用了! root不为null,attachToRoot为true的话,会在加载的布局文件最外层嵌套一层root布局; 为false的话,则root失去作用! 简单理解就是:是否为加载的布局添加一个root的外层容器~!

3. 通过LayoutInflater.LayoutParams来设置相关的属性

比如RelativeLayout还可以通过addRule方法添加规则,就是设置位置:是参考父容器呢? 还是参考子控件?又或者设置margin等等,这个由你决定~

4. Java代码加载布局的流程

第一种方法:通过LayoutInflate的inflate()方法加载了activity_main布局,获得了外层容器, 接着addView添加按钮进容器,最后setContentView();

第二种方法:因为我们已经通过setContetView()方法加载了布局,此时我们就可以通过 findViewById找到这个外层容器,接着addView,最后setContentView()即可!

另外,关于这个setContentView( )他设置的视图节点是整个XML的根节点!

参考文档:

  1. 官方文档:https://developer.android.com/reference/android/view/LayoutInflater
  2. runoob:https://www.runoob.com/w3cnote/android-tutorial-layoutinflater.html

标签:总结,LayoutInflater,setContentView,布局,inflate,root,加载
来源: https://blog.csdn.net/qq_40714317/article/details/117666100