【Android源码】LayoutInflater 分析

148 阅读3分钟

通常情况下我们使用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。