Android LayoutInflater 使用详解 View.inflate 的加载原理

志在巅峰的攀登者,不会陶醉在沿途的某个脚印之中,在码农的世界里,优美的应用体验,来源于程序员对细节的处理以及自我要求的境界,年轻人也是忙忙碌碌的码农中一员,每天、每周,都会留下一些脚印,就是这些创作的内容,有一种执着,就是不知为什么,如果你迷茫,不妨来瞅瞅码农的轨迹。

如果你有兴趣 你可以关注一下公众号 biglead 来获取最新的学习资料。

LayoutInflater 是用来将 layout.xml 布局文件添加到指定 View 中,或者是将 layout.xml 布局文件转化为对应的 View 对象。


1 LayoutInflater 的获取方式

第一种方式: 从给定的上 Context 下文中获取LayoutInflater:

LayoutInflater  inflater = LayoutInflater.from(context);

或者是

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

第二种方式:在Activity中直接获取LayoutInflater:

LayoutInflater inflater = getLayoutInflater();

从源码分析的角度,无论哪种方式,最终都是使用的 context.getSystemService 这种方式。

2 获取View

2.1 View.inflate

我们通常会将 layout 布局文件加载成View , 会这样来写

 /**
  * 将 Layout 文件 加载 View
  * 参数一 上下文对象
  * 参数二 布局文件 ID
  * 参数三 不为null 时自动将这个布局文件 加载到这个 root 中去  null 代表不添加
  */
View inflate = View.inflate(mContext, R.layout.activity_list1_item, null);

它调用的源码如下


    /**
     * Inflate a view from an XML resource.  This convenience method wraps the {@link
     * LayoutInflater} class, which provides a full range of options for view inflation.
     *
     * @param context The Context object for your activity or application.
     * @param resource The resource ID to inflate
     * @param root A view group that will be the parent.  Used to properly inflate the
     * layout_* parameters.
     * @see LayoutInflater
     */
    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

所以它实际上还是调用的 LayoutInflater.inflate 方法实现的加载。

2.2 LayoutInflater.inflate
/**
   *  参数一 上下文对象
   */
  LayoutInflater layoutInflater = LayoutInflater.from(mContext);
  /**
   * 将 Layout 文件 加载 View
   * 参数一 布局文件 ID
   * 参数二 不为null 时 会测量这个 parent 的大小来 作为 inflate 的父组件大小参考
   * 参数三 true 将加载的 layout 布局文件 自动添加到 parent 中去
   */
  View inflate = layoutInflater.inflate(R.layout.activity_list1_item, parent,false);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早起的年轻人

创作源于分享

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值