學習過程中遇到什么問題或者想獲取學習資源的話嫩挤,歡迎加入Android學習交流群,群號碼:364595326? 我們一起學Android!
轉載自blog.csdn.net/u013356254/article/details/55052363
源碼分析之LayoutInflater
簡介
基于5.0的framework源碼進行分析惰匙,通過這篇文章我們能了解:
LayoutInflater的系統(tǒng)級服務的注冊過程
inflate填充的過程
ViewStub,merge,include的加載過程
LayoutInflater系統(tǒng)服務的注冊過程
我們經常調用
context.getSystemService(Context.LAYOUT_INFLATE_SERVICE)
獲得LayoutInflater對象。那么這個對象是什么時候注冊到Context中的呢?這個對象的具體實現(xiàn)類是誰铃将?
LayoutInflater這個服務项鬼,是在創(chuàng)建Activity的時候,作為baseContext傳遞給Activity的劲阎。接下來我們看源碼過程秃臣。
我們知道Activity的創(chuàng)建過程是在ApplicationThread的performLaunchActivity方法中。那么接下來我們分析這個方法
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
/*/
Activity activity = null;
try{
// 通過Instrumentation類創(chuàng)建Activity
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
}catch(Exeception e){}
/*/
// 創(chuàng)建Context過程哪工,也就是baseContext
Context appContext = createBaseContextForActivity(r, activity);
// 關聯(lián)activity和baseContext
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);
}
那么接下來我們只要分析
Context appContext = createBaseContextForActivity(r, activity);
這個方法即可奥此,源碼繼續(xù)
private Context createBaseContextForActivity(ActivityClientRecord r, final Activity activity) {
// 通過調用ContextImpl的靜態(tài)方法創(chuàng)建baseContext對象
ContextImpl appContext = ContextImpl.createActivityContext(
this, r.packageInfo, r.token, displayId, r.overrideConfig);
appContext.setOuterContext(activity);
return baseContext;
}
接下來分析
ContextImpl.createActivityContext(
this, r.packageInfo, r.token, displayId, r.overrideConfig);
appContext.setOuterContext(activity);
接下來我們分析下ContextImpl這個類,發(fā)現(xiàn)其有一個成員變量
// 在這里注冊系統(tǒng)級別的服務
// The system service cache for the system services that are cached per-ContextImpl.
final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();
SystemServiceRegistry類有個靜態(tài)代碼塊雁比,完成了常用服務的注冊稚虎,代碼如下
static{
// 注冊LayoutLAYOUT_INFLATER_SERVICE系統(tǒng)服務,具體實現(xiàn)類是PhoneLayoutInflater
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
return new PhoneLayoutInflater(ctx.getOuterContext());
}});
// 注冊AM
registerService(Context.ACTIVITY_SERVICE, ActivityManager.class,
new CachedServiceFetcher() {
@Override
public ActivityManager createService(ContextImpl ctx) {
return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
}});
// 注冊WM
registerService(Context.WINDOW_SERVICE, WindowManager.class,
new CachedServiceFetcher() {
@Override
public WindowManager createService(ContextImpl ctx) {
return new WindowManagerImpl(ctx);
}});
// 等等
}
接下來我們看inflate過程偎捎,下面是整個inflate過程
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 {
// 循環(huán)找到第一個view節(jié)點蠢终,
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
// 這里判斷是否是第一個view節(jié)點
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
// 解析merge標簽
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException(" can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
// 通過rInflate方法將merge標簽下的孩子直接合并到root上序攘,這樣減少一層布局,達到減少viewTree的目的
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// 調用反射創(chuàng)建view對象
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// 如果view的父容器不為null寻拂,并且attachToRoot未true得話程奠,這里只是讓剛剛通過反射創(chuàng)建的view使用root(父容器的布局參數)
temp.setLayoutParams(params);
}
}
// 通過深度遍歷temp下的節(jié)點,之后將節(jié)點依次添加到剛剛通過反射創(chuàng)建的temp對象上祭钉,因為采用的是深度優(yōu)先遍歷算法瞄沙,因此viewTree的層級很深的話,會影響遍歷的性能
rInflateChildren(parser, temp, attrs, true);
// 判斷剛剛創(chuàng)建的temp對象是否添加到父節(jié)點上.
// 滿足兩個條件1 父節(jié)點(root)不為null慌核,2 attachToRoot=true
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 設置result
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
final InflateException ie = new InflateException(e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
// 返回
return result;
}
}
通過上面分析距境,我們對inflate的整體過程有了一個了解,也見到了merge標簽(經常作為布局文件根節(jié)點垮卓,來達到減少viewTree的層次)
接下來垫桂,我們分析4個方法
rInflate(parser, root, inflaterContext, attrs, false);,其實不管是根節(jié)點為merge還是普通的view(最終都會用這個方法)粟按,深度遍歷添加view
下面是代碼
// 深度遍歷添加孩子
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)) {
// 如果我們調用了View.setTag()诬滩,將會執(zhí)行下面代碼
parseViewTag(parser, parent, attrs);
// include不能作為根節(jié)點
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException(" cannot be the root element");
}
// 這里解析include標簽代碼
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
// merge一定是根節(jié)點
throw new InflateException(" 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最終還會調用rInflate(parser, parent, parent.getContext(), attrs, finishInflate);方法
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) {
// viewTree填充完畢灭将,回調自定義view經常使用的onFinishInflate方法
parent.onFinishInflate();
}
}
rInflateChildren(parser, view, attrs, true);方法
// 直接調用rInflate()實現(xiàn)ViewTree
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
createViewFromTag(root, name, inflaterContext, attrs);方法疼鸟,這個方法其實處理了自定義view和系統(tǒng)view的創(chuàng)建。最終調用了下面方法
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// 設置view默認樣式
if (!ignoreThemeAttr) {
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
}
try {
View view;
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {//創(chuàng)建系統(tǒng)view的方法宗侦,因為系統(tǒng)view的標簽不是完整類名愚臀,需要會在 onCreateView中完成拼接(拼接出系統(tǒng)view的完整類名)
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
//自定義view的創(chuàng)建
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
}
}
接下來我們分析 createView(String name, String prefix, AttributeSet attrs)方法忆蚀,系統(tǒng)view的創(chuàng)建矾利,最終也會調用createView方法。只不過在前面拼接上了系統(tǒng)view的包名馋袜。
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
// 獲取view的構造方法
Constructor constructor = sConstructorMap.get(name);
// 驗證
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class clazz = null;
try {
if (constructor == null) {
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);
// 將view的構造方法緩存起來
sConstructorMap.put(name, constructor);
} else {
/*/
}
Object[] args = mConstructorArgs;
args[1] = attrs;
// 反射創(chuàng)建view對象
final View view = constructor.newInstance(args);
// 對viewStub進行處理
if (view instanceof ViewStub) {
// 給ViewStub設置LayoutInfalter.什么時候inflate男旗,什么時候viewStub的內容才顯示,(比GONE性能好)
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 {
}
}
總結
系統(tǒng)服務的填充過程欣鳖,是在ContextImpl中完成注冊的
LayoutInflater的實現(xiàn)類是PhoneLayoutInflater
如果僅僅使用父容器的布局參數察皇,可以使用inflater.inflate(layoutId,parent,false);
onFinishInflate()方法是在viewTree遍歷完成之后,調用的
merge標簽只能是根節(jié)點泽台,include標簽不能是根節(jié)點什荣。
布局優(yōu)化
view的inflate的過程是深度遍歷,因此應該盡量減少viewTree的層次怀酷,可以考慮使用merge標簽
如果我們不知道view什么時候填充的時候稻爬,可以使用ViewStub標簽,什么時候用什么時候填充
include是提升復用的