前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >android之inflater介绍

android之inflater介绍

作者头像
李小白是一只喵
发布2020-12-02 11:53:12
3930
发布2020-12-02 11:53:12
举报
文章被收录于专栏:算法微时光算法微时光

image.png

LayoutInflater(布局加载器)

开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。

不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化.

而findViewById()是找xml布局文件下的具体widget控件(如 Button、TextView等)。

使用场景:

  • 对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入。
  • 对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。
代码语言:javascript
复制
public abstract class LayoutInflater extends Object  

使用方式

获得 LayoutInflater 实例的三种方式:

代码语言:javascript
复制
LayoutInflater inflater = getLayoutInflater();  //调用Activity的getLayoutInflater()

LayoutInflater localinflater =(LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);

LayoutInflater inflater = LayoutInflater.from(context);  
三种方法的关系

getLayoutInflater方法是Activity方法,调用 PhoneWindow 的getLayoutInflater()方法,看一下该源代码:

代码语言:javascript
复制
 public PhoneWindow(Context context) {  
        super(context);  
        mLayoutInflater = LayoutInflater.from(context);  
}  

内部其实调用了LayoutInflater.from(context)方法。 LayoutInflater.from(context)实现源码:

代码语言:javascript
复制
public static LayoutInflater from(Context context) {   
    LayoutInflater LayoutInflater =   
            (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);   
    if (LayoutInflater == null) {   
        throw new AssertionError("LayoutInflater not found.");   
    }   
    return LayoutInflater;   
} 

内部其实调用的是getSystemService方法。

inflate api

代码语言:javascript
复制
public View inflate (int resource, ViewGroup root)
public View inflate (XmlPullParser parser, ViewGroup root)
public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)
public View inflate (int resource, ViewGroup root, boolean attachToRoot)

使用代码:

代码语言:javascript
复制
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);  
View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test));  
EditText editText = (EditText)view.findViewById(R.id.content);  
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LayoutInflater(布局加载器)
  • 使用方式
    • 三种方法的关系
    • inflate api
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档