轉載請注明出處:http://blog.csdn.net/fishle123/article/details/51039293
在Android裡面,經常使用LayoutInflater來加載布局。這裡結合源碼分析一下LayoutInflater是如何加載布局的。
LayoutInflater一個常見的用法如下:
private View inflateView(Context context, int resID) {
LayoutInflater inflater = LayoutInflater.from(context);
//或者也可以這樣擷取LayoutInlfater
//LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(resID, null);
}
這樣簡單的幾行代碼就可以就把使用xml定義的布局轉化為對應View。
下面就從LayoutInflater的inflate方法開始分析LayoutInflater的工作過程。
/**
* Obtains the LayoutInflater from the given context.
*/
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;
}
從這裡可以看到,LayoutInlfater最終是通過getSystemService來擷取的。如果大家對Context有一定的了解就會知道,Context的實作類是ContextImpl,這裡直接去看ContextImpl的源碼:
//https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/ContextImpl.java
@Override
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
繼續看SystemServiceRegistry的getSystemService的源碼:
/**https://github.com/android/platform_frameworks_base/blob/master/core/java/android/app/SystemServiceRegistry.java
* Gets a system service from a given context.
*/
public static Object getSystemService(ContextImpl ctx, String name) {
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
SYSTEM_SERVICE_FETCHERS定義如下:
// Service registry information.
// This information is never changed once static initialization has completed.
private static final HashMap<Class<?>, String> SYSTEM_SERVICE_NAMES =
new HashMap<Class<?>, String>();
private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
new HashMap<String, ServiceFetcher<?>>();
可以看到,SYSTEM_SERVICE_FETCHERS其實是一個HashMap,它儲存了系統提供的各種ServiceFetcher,在ServiceFetcher裡面儲存有對應的Service對象。在SystemServiceRegistry中會在靜态語句塊中調用registerService來注冊系統提供的Service,比如LayoutInflater也是在這裡注冊的(見第21--26行):
static {
......
registerService(Context.ACTIVITY_SERVICE, ActivityManager.class,
new CachedServiceFetcher<ActivityManager>() {
@Override
public ActivityManager createService(ContextImpl ctx) {
return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
}});
registerService(Context.ALARM_SERVICE, AlarmManager.class,
new CachedServiceFetcher<AlarmManager>() {
@Override
public AlarmManager createService(ContextImpl ctx) {
IBinder b = ServiceManager.getService(Context.ALARM_SERVICE);
IAlarmManager service = IAlarmManager.Stub.asInterface(b);
return new AlarmManager(service, ctx);
}});
......
//注冊LayoutInlfater
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher<LayoutInflater>() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
return new PhoneLayoutInflater(ctx.getOuterContext());
}});
......
}
/**
* Statically registers a system service with the context.
* This method must be called during static initialization only.
*/
private static <T> void registerService(String serviceName, Class<T> serviceClass,
ServiceFetcher<T> serviceFetcher) {
SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
}
到這裡,我們已經弄清楚LayoutInflater是如何建立和擷取的了,下面來看看inflate方法是如何加載布局的。先看inflate的源碼:
/**
* Inflate a new view hierarchy from the specified xml resource. Throws
* {@link InflateException} if there is an error.
*
* @param resource ID for an XML layout resource to load (e.g.,
* <code>R.layout.main_page</code>)
* @param root Optional view to be the parent of the generated hierarchy.
* @return The root View of the inflated hierarchy. If root was supplied,
* this is the root View; otherwise it is the root of the inflated
* XML file.
*/
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
inflate(int resource, ViewGroup root)最終會調用inflate(int resource, ViewGroup root, boolean attachToRoot)
,而後者會調用inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot),繼續看源碼:
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root;
try {
// 查找布局的根節點.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
......
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
.....
// 加載子布局
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);//将布局添加到父節點中
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (Exception e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
其實inflate的邏輯還是比較簡單的,從inflate的參數可以看出,它使用的Pull方式來分析xml布局檔案。遇到一個View節點後,會調用createViewFromTag來建立對應的View執行個體。如果該View節點有父節點(root),還會為該View生成對應布局參數LayoutParams,即我們為該節點使用layout_xxx屬性可以生效。但是我們在Activity裡面調用setContentView的時候,在外層會有一個FrameLayout,是以這時候root是不等于null的,是以我們在根節點中使用layout_xxx屬性時都是可以生效的。這裡重點看一下第37行和第57行,在37行先建立了目前布局的根節點,然後在57行調用 rInflateChildren(parser, temp, attrs, true)來加載子布局。
下面先來看一下createViewFromTag是怎樣建立View的,在createViewFromTag内部又會調用createView,這裡直接看createView的源碼:
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor<? extends View> constructor = sConstructorMap.get(name);
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
//如果constructor為null,就先加載相應的class
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
//将構造函數constructor儲存起來,後續遇到相同的View的時候可以直接拿來用
sConstructorMap.put(name, constructor);
} else {
// If we have a filter, apply it to cached constructor
if (mFilter != null) {
// Have we seen this name before?
Boolean allowedState = mFilterMap.get(name);//複用之前儲存的構造函數
if (allowedState == null) {
// New class -- remember whether it is allowed
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
Object[] args = mConstructorArgs;
args[1] = attrs;
//建立相應的執行個體
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
} catch (NoSuchMethodException e) {
......
} catch (ClassCastException e) {
......
} catch (ClassNotFoundException e) {
.......
} catch (Exception e) {
......
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
在第3行會先去sConstructorMap查找對應View的構造函數是否已經緩存,如果有就直接拿來用,當然第一次遇到該View的時候是不存在的,是以9--23行會加載對應的class,然後找到構造函數,找到之後會儲存到sConstructorMap,這樣下次再遇到相同的View就不用再去重新加載class了。接着47行會調用newInstance來建立對應的View的執行個體。這裡可以看到從xml檔案中解析到View的名字後,會使用反射的方式來建立對應的執行個體。
最後,再來看一下 rInflateChildren(parser, temp, attrs, true)的源碼:
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
直接看12--39行,在while循環中會逐個節點的分析xml布局,然後調用createViewFromTag建立對應的View。接着在36行遞歸調用rInflateChildren來分析子布局。因為這是使用的是遞歸的方式,是以我們的布局不能嵌套太多層級了。
我們可以看到inflate加載布局的過程其實可以分為兩步:第一步,先解析整個xml布局的根節點,并建立對應的執行個體(通過反射來建立);第二步,通過遞歸的方式來分析子布局并建立對應的執行個體。
到此為止,我們就弄清楚LayoutInflater是如何加載布局的了。