美文网首页
View.inflate()和LayoutInflater.in

View.inflate()和LayoutInflater.in

作者: 草帽团长 | 来源:发表于2018-03-01 11:47 被阅读0次

一、LayoutInflater.inflate()


该方法适用于所有布局填充的的场景,但使用前需要先实例化LayoutInflater对象

1. 获取LayoutInflater实例

  • 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)

该方法,实际还是调用了上一个方法

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
    return inflate(resource, root, root != null);
}

二、 View.inflate()


这个是View类的静态方法,可直接调用,实际上还是使用了LayoutInflater,所以,它没有直接使用LayoutInflater.inflate()强大

public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
    LayoutInflater factory = LayoutInflater.from(context);
    return factory.inflate(resource, root);
}

参数含义:

  • context:上下文
  • resource:布局资源
  • root:resource生成view对象要填入的父布局。为null,则返回resource生成view对象,否则将view填入到root中,以root作为根布局返回

三、总结


View.inflate()是封装了LayoutInflater的inflate()方法,由于是静态方法,比较简便;但LayoutInflater相当于比View多了一个三个参数的inflate()方法,功能更强大


个人总结,水平有限,如果有错误,希望大家能给留言指正!如果对您有所帮助,可以帮忙点个赞!如果转载,希望可以留言告知并在显著位置保留草帽团长的署名和标明文章出处!最后,非常感谢您的阅读!

相关文章

网友评论

      本文标题:View.inflate()和LayoutInflater.in

      本文链接:https://www.haomeiwen.com/subject/ekdgxftx.html