【Android源码】LayoutInflater 分析

通常情况下我们使用LayoutInflater较为常见的地方是ListView的getView中:

View view = LayoutInflater.from(context).inflate(R.layout.xxx, null);

通常情况下我们使用LayoutInflater.from(context)来获取LayoutInflater服务,我们来看看LayoutInflater服务是如何实现的。

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;
}

可以看到from(context)是通过context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法,继续跟踪之后,得知Context类是个抽象类。

而getView中使用的context的实现类是什么呢?
在每个Activity、Service、Application中都存在一个Context对象,所以Context对象的总个数为Activity+Service+1。而ListView通常情况下出现在Activity中,所以我们以Activity的Context对象来分析。

一个Activity的入口是ActivityThread的main函数,在main函数中创建ActivityThread对象,并且启动Handler,创建新的Activity、新的Context对象,并将该对象传递给Activity

public static void main(String[] args) {
   
   Process.setArgV0("<pre-initialized>");

   Looper.prepareMainLooper();

   ActivityThread thread = new ActivityThread();
   thread.attach(false);

   if (sMainThreadHandler == null) {
       sMainThreadHandler = thread.getHandler();
   }

   if (false) {
       Looper.myLooper().setMessageLogging(new
               LogPrinter(Log.DEBUG, "ActivityThread"));
   }

   // End of event ActivityThreadMain.
   Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
   Looper.loop();
}

在main函数中,创建并调用了attach方法传递false(非系统应用)

private void attach(boolean system) {
   sCurrentActivityThread = this;
   mSystemThread = system;
   if (!system) {
       ViewRootImpl.addFirstDrawHandler(new Runnable() {
           @Override
           public void run() {
               ensureJitEnabled();
           }
       });
       android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                               UserHandle.myUserId());
       RuntimeInit.setApplicationObject(mAppThread.asBinder());
       final IActivityManager mgr = ActivityManagerNative.getDefault();
       try {
           mgr.attachApplication(mAppThread);
       } catch (RemoteException ex) {
           throw ex.rethrowFromSystemServer();
       }
   }
}

在attach方法中通过Binder机制和ActivityManagerService通信,最终调用handleLaunchActivity方法

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
   Activity a = performLaunchActivity(r, customIntent);
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
   Activity activity = null;
   try {
       java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
       // 创建activity
       activity = mInstrumentation.newActivity(
               cl, component.getClassName(), r.intent);
   } catch (Exception e) {
       if (!mInstrumentation.onException(activity, e)) {
           throw new RuntimeException(
               "Unable to instantiate activity " + component
               + ": " + e.toString(), e);
       }
   }

   try {
      // 创建Application
       Application app = r.packageInfo.makeApplication(false, mInstrumentation);
       
       if (activity != null) {
            // 创建Context
           Context appContext = createBaseContextForActivity(r, activity);
           CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
           Configuration config = new Configuration(mCompatConfiguration);
           // 将相关对象attach到activity中
           activity.attach(appContext, this, getInstrumentation(), r.token,
                   r.ident, app, r.intent, r.activityInfo, title, r.parent,
                   r.embeddedID, r.lastNonConfigurationInstances, config,
                   r.referrer, r.voiceInteractor, window);
           // 调用onCreate方法
           if (r.isPersistable()) {
               mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
           } else {
               mInstrumentation.callActivityOnCreate(activity, r.state);
           }
       }
       r.paused = true;

       mActivities.put(r.token, r);

   } catch (SuperNotCalledException e) {
       throw e;

   }

   return activity;
}

private Context createBaseContextForActivity(ActivityClientRecord r, final Activity activity) {
    // 创建Context对象
   ContextImpl appContext = ContextImpl.createActivityContext(
           this, r.packageInfo, r.token, displayId, r.overrideConfig);
   return baseContext;
}

最终我们可以发现创建的Context对象的实现类是ContextImpl。我们继续观察ContextImpl:

// The system service cache for the system services that are cached per-ContextImpl.
// 获取系统服务
final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();

在SystemServiceRegistry中:

// service容器
private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS = new HashMap<String, ServiceFetcher<?>>();

// 注册服务器
private static <T> void registerService(String serviceName, Class<T> serviceClass,
       ServiceFetcher<T> serviceFetcher) {
   SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
   // 将服务放到service容器中
   SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
}

// 静态代码块,当第一次加载该类的时候就将执行将服务创建出来
static {
   registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
           new CachedServiceFetcher<AccessibilityManager>() {
       @Override
       public AccessibilityManager createService(ContextImpl ctx) {
           return AccessibilityManager.getInstance(ctx);
       }});
   ...
}

// 获取系统服务
public static Object getSystemService(ContextImpl ctx, String name) {
   ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
   return fetcher != null ? fetcher.getService(ctx) : null;
}

在ContextImpl中,当虚拟机第一次加载的时候就会注册各种服务,其中就包含LayoutInflater Service,将这些服务以键值对的形式存储在map中,当使用的时候只要通过key就可以获取对应的服务对象。

在静态代码块中,我们终于找到了LayoutInflater注册的代码:

registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
           new CachedServiceFetcher<LayoutInflater>() {
       @Override
       public LayoutInflater createService(ContextImpl ctx) {
           return new PhoneLayoutInflater(ctx.getOuterContext());
       }});

原来LayoutInflater是通过PhoneLayoutInflater创建出来的,我们再找到PhoneLayoutInflater类:

public class PhoneLayoutInflater extends LayoutInflater {
    private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };
    public PhoneLayoutInflater(Context context) {
        super(context);
    }

    protected PhoneLayoutInflater(LayoutInflater original, Context newContext) {
        super(original, newContext);
    }

    /** Override onCreateView to instantiate names that correspond to the
        widgets known to the Widget factory. If we don't find a match,
        call through to our super class.
    */
    @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
        for (String prefix : sClassPrefixList) {
            try {
                View view = createView(name, prefix, attrs);
                if (view != null) {
                    return view;
                }
            } catch (ClassNotFoundException e) {
                // In this case we want to let the base class take a crack
                // at it.
            }
        }

        return super.onCreateView(name, attrs);
    }

    public LayoutInflater cloneInContext(Context newContext) {
        return new PhoneLayoutInflater(this, newContext);
    }
}

核心方法就是onCreateView方法,该方法通过将传递过来的View前面加上"android.widget.","android.webkit.","android.app."用来得到该内置View对象的完整路径,最后根据路径来创建出对应的View。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353

推荐阅读更多精彩内容