源碼分析之LayoutInflater

學習過程中遇到什么問題或者想獲取學習資源的話嫩挤,歡迎加入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)建過程是在ApplicationThreadperformLaunchActivity方法中。那么接下來我們分析這個方法

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是提升復用的

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末蜕依,一起剝皮案震驚了整個濱河市桅锄,隨后出現(xiàn)的幾起案子琉雳,更是在濱河造成了極大的恐慌,老刑警劉巖友瘤,帶你破解...
    沈念sama閱讀 223,126評論 6 520
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件翠肘,死亡現(xiàn)場離奇詭異,居然都是意外死亡辫秧,警方通過查閱死者的電腦和手機束倍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,421評論 3 400
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來茶没,“玉大人肌幽,你說我怎么就攤上這事∽グ耄” “怎么了喂急?”我有些...
    開封第一講書人閱讀 169,941評論 0 366
  • 文/不壞的土叔 我叫張陵,是天一觀的道長笛求。 經常有香客問我廊移,道長,這世上最難降的妖魔是什么探入? 我笑而不...
    開封第一講書人閱讀 60,294評論 1 300
  • 正文 為了忘掉前任狡孔,我火速辦了婚禮,結果婚禮上蜂嗽,老公的妹妹穿的比我還像新娘苗膝。我一直安慰自己,他們只是感情好植旧,可當我...
    茶點故事閱讀 69,295評論 6 398
  • 文/花漫 我一把揭開白布辱揭。 她就那樣靜靜地躺著,像睡著了一般病附。 火紅的嫁衣襯著肌膚如雪问窃。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,874評論 1 314
  • 那天完沪,我揣著相機與錄音域庇,去河邊找鬼。 笑死覆积,一個胖子當著我的面吹牛听皿,可吹牛的內容都是我干的。 我是一名探鬼主播宽档,決...
    沈念sama閱讀 41,285評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼尉姨,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了雌贱?” 一聲冷哼從身側響起啊送,我...
    開封第一講書人閱讀 40,249評論 0 277
  • 序言:老撾萬榮一對情侶失蹤偿短,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后馋没,有當地人在樹林里發(fā)現(xiàn)了一具尸體昔逗,經...
    沈念sama閱讀 46,760評論 1 321
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,840評論 3 343
  • 正文 我和宋清朗相戀三年篷朵,在試婚紗的時候發(fā)現(xiàn)自己被綠了勾怒。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,973評論 1 354
  • 序言:一個原本活蹦亂跳的男人離奇死亡声旺,死狀恐怖笔链,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情腮猖,我是刑警寧澤鉴扫,帶...
    沈念sama閱讀 36,631評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站澈缺,受9級特大地震影響坪创,放射性物質發(fā)生泄漏。R本人自食惡果不足惜姐赡,卻給世界環(huán)境...
    茶點故事閱讀 42,315評論 3 336
  • 文/蒙蒙 一莱预、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧项滑,春花似錦依沮、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,797評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至摘完,卻和暖如春姥饰,著一層夾襖步出監(jiān)牢的瞬間傻谁,已是汗流浹背孝治。 一陣腳步聲響...
    開封第一講書人閱讀 33,926評論 1 275
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留审磁,地道東北人谈飒。 一個月前我還...
    沈念sama閱讀 49,431評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像态蒂,于是被迫代替她去往敵國和親杭措。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,982評論 2 361

推薦閱讀更多精彩內容

  • ¥開啟¥ 【iAPP實現(xiàn)進入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程钾恢,因...
    小菜c閱讀 6,453評論 0 17
  • 用法獲取LayoutInflater 首先要注意LayoutInflater本身是一個抽象類手素,我們不可以直接通過n...
    我本和圖閱讀 872評論 0 0
  • 有段時間沒寫博客了鸳址,感覺都有些生疏了呢。最近繁忙的工作終于告一段落泉懦,又有時間寫文章了稿黍,接下來還會繼續(xù)堅持每一周篇的...
    justin_pan閱讀 552評論 0 2
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法崩哩,內部類的語法巡球,繼承相關的語法,異常的語法邓嘹,線程的語...
    子非魚_t_閱讀 31,669評論 18 399
  • 主產于吉林省延邊朝鮮族自治州酣栈。圓形邊緣里面帶有,點狀紅暈汹押,酷似蘋果矿筝,故名蘋果梨。 延邊蘋果梨系有1921年從朝鮮引...
    鏗鏘玫瑰999閱讀 1,522評論 0 0