广告也精彩

以下文章对LayoutInflater总结的不错,摘抄于此,部分内容稍微改动。

在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。

具体作用:

  1. 对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
  2. 对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。

Android中获取LayoutInflater 的方式有如下三种:

//方法1
LayoutInflater inflater_1 = getLayoutInflater(); // 调用Activity的getLayoutInflater()

//方法2
LayoutInflater inflater_2 = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

//方法3
LayoutInflater inflater_3 = LayoutInflater.from(mContext);

然而我们从源码中看的话,发现上面三种方法的本质都是一样的。

在(\framework\base\core\java\android\view\LayoutInflater.java)

中LayoutInflater 是个抽象函数

public abstract class LayoutInflater
{
     ....
}

我们在Activity中调用直接是使用Activity中封装的方法,从getLayoutInflater()开始往前看看LayoutInflater是怎么初始化的。

在 (\framework\base\core\java\android\app\Activity.java)

//Activity是调用PhoneWindow中初始化的LayoutInflater
public LayoutInflater getLayoutInflater() {
return getWindow().getLayoutInflater();
}

//获取PhoneWindow
public Window getWindow() {
return mWindow;
}

//PhoneWindow的初始化
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor) {

   ....

mWindow = new PhoneWindow(this);

   ....

}

在(\framework\base\core\java\com\android\internal\policy\PhoneWindow.java)

//获取初始化过的mLayoutInflater
@Override
public LayoutInflater getLayoutInflater() {
return mLayoutInflater;
}

//而mLayoutInflater是调用LayoutInflater中的from方法初始化的
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}

又在(\framework\base\core\java\android\view\LayoutInflater.java)

//LayoutInflater.java中的初始化方法
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;
}

经过上面代码的流程,发现3中LayoutInflater的获取本质是一样的。

 历史上的今天

版权声明 1、 本站名称: 91易搜
2、 本站网址: 91es.com3xcn.com
3、 本站文章: 部分来源于网络,仅供站长学习和参考,若侵权请留言
广告也精彩

相关文章

广告也精彩

暂无评论

评论审核已启用。您的评论可能需要一段时间后才能被显示。

暂无评论...

网站升级中

公告

近期网站升级中,可能存在一些bug。欢迎反馈 https://www.91es.com/we.html

本站域名

本站域名 : 91es.com3xcn.com。本站邮箱 : 站长邮箱 i@oorr.cn,通知邮箱we@oorr.cn ,如有更新,请看公告 。