一、LayoutInflater.inflate()
1.获取Layoutlnflater实例
getLayoutInflater()
可以在Activity,Fragment中使用,但在Fragment中使用需传入一个bundle
// Activity中使用
LayoutInflater layoutInflater = getLayoutInflater();
// Fragment中使用
LayoutInflater layoutInflater = getLayoutInflater(savedInstanceState);
getSystemService();
这个为Context的方法,只要有上下文就能调用
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater.from();
这个是LayoutInflater的静态方法,传入上下文即可
LayoutInflater inflater = LayoutInflater.from(this);
2. LayoutInflater.inflate()的重载
常用的是下面两种:
inflate(int resource,ViewGroup root,boolean attachToRoot)
resource:布局资源id
root:resource生成view对象要填入的父布局。为null,则返回的view就是布局资源;否则,需要参照第三个参数
attachToRoot:是否将resource生成view对象填入root,以root作为最终返回view的根布局。 false,root不为null,则提供root的LayoutParams约束resource生成的view;true,root不为null,以root作为最终返回view的根布局
inflate(int resource,ViewGroup root)
resource:布局资源
root:resource生成view对象要填入的父布局。为null,则返回的view就是布局资源的根布局;否则,返回的view以传入的root为根布局(相当于上面的那个第三个参数为true)
该方法,实际还是调用了上一个方法
publicViewinflate(@LayoutResintresource, @Nullable ViewGroup root){return inflate(resource, root, root !=null);}
二、 View.inflate()
这个是View类的静态方法,可直接调用,实际上还是使用了LayoutInflater,所以,它没有直接使用LayoutInflater.inflate()强大
publicstaticViewinflate(Context context, @LayoutResintresource, ViewGroup root){ LayoutInflater factory = LayoutInflater.from(context);returnfactory.inflate(resource, root);}
参数含义:
context:上下文
resource:布局资源
root:resource生成view对象要填入的父布局。为null,则返回resource生成view对象,否则将view填入到root中,以root作为根布局返回
三、总结
View.inflate()是封装了LayoutInflater的inflate()方法,由于是静态方法,比较简便;但LayoutInflater相当于比View多了一个三个参数的inflate()方法,功能更强大
网友评论