源碼分析之LayoutInflater

學習過程中遇到什么問題或者想獲取學習資源的話,歡迎加入Android學習交流群,群號碼:364595326? 我們一起學Android!

轉載自blog.csdn.net/u013356254/article/details/55052363

源碼分析之LayoutInflater

簡介

基于5.0的framework源碼進行分析,通過這篇文章我們能了解:

LayoutInflater的系統級服務的注冊過程

inflate填充的過程

ViewStub,merge,include的加載過程

LayoutInflater系統服務的注冊過程

我們經常調用

context.getSystemService(Context.LAYOUT_INFLATE_SERVICE)

獲得LayoutInflater對象。那么這個對象是什么時候注冊到Context中的呢?這個對象的具體實現類是誰?

LayoutInflater這個服務,是在創建Activity的時候,作為baseContext傳遞給Activity的。接下來我們看源碼過程。

我們知道Activity的創建過程是在ApplicationThreadperformLaunchActivity方法中。那么接下來我們分析這個方法

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

/*/

Activity activity = null;

try{

// 通過Instrumentation類創建Activity

java.lang.ClassLoader cl = r.packageInfo.getClassLoader();

activity = mInstrumentation.newActivity(

cl, component.getClassName(), r.intent);

}catch(Exeception e){}

/*/

// 創建Context過程,也就是baseContext

Context appContext = createBaseContextForActivity(r, activity);

// 關聯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);

這個方法即可,源碼繼續

private Context createBaseContextForActivity(ActivityClientRecord r, final Activity activity) {

// 通過調用ContextImpl的靜態方法創建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這個類,發現其有一個成員變量

// 在這里注冊系統級別的服務

// The system service cache for the system services that are cached per-ContextImpl.

final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();

SystemServiceRegistry類有個靜態代碼塊,完成了常用服務的注冊,代碼如下

static{

// 注冊LayoutLAYOUT_INFLATER_SERVICE系統服務,具體實現類是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 {

// 循環找到第一個view節點,

int type;

while ((type = parser.next()) != XmlPullParser.START_TAG &&

type != XmlPullParser.END_DOCUMENT) {

// Empty

}

// 這里判斷是否是第一個view節點

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 {

// 調用反射創建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得話,這里只是讓剛剛通過反射創建的view使用root(父容器的布局參數)

temp.setLayoutParams(params);

}

}

// 通過深度遍歷temp下的節點,之后將節點依次添加到剛剛通過反射創建的temp對象上,因為采用的是深度優先遍歷算法,因此viewTree的層級很深的話,會影響遍歷的性能

rInflateChildren(parser, temp, attrs, true);

// 判斷剛剛創建的temp對象是否添加到父節點上.

// 滿足兩個條件1 父節點(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標簽(經常作為布局文件根節點,來達到減少viewTree的層次)

接下來,我們分析4個方法

rInflate(parser, root, inflaterContext, attrs, false);,其實不管是根節點為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(),將會執行下面代碼

parseViewTag(parser, parent, attrs);

// include不能作為根節點

} 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一定是根節點

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()實現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和系統view的創建。最終調用了下面方法

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 {//創建系統view的方法,因為系統view的標簽不是完整類名,需要會在 onCreateView中完成拼接(拼接出系統view的完整類名)

if (-1 == name.indexOf('.')) {

view = onCreateView(parent, name, attrs);

} else {

//自定義view的創建

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)方法,系統view的創建,最終也會調用createView方法。只不過在前面拼接上了系統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;

// 反射創建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 {

}

}

總結

系統服務的填充過程,是在ContextImpl中完成注冊的

LayoutInflater的實現類是PhoneLayoutInflater

如果僅僅使用父容器的布局參數,可以使用inflater.inflate(layoutId,parent,false);

onFinishInflate()方法是在viewTree遍歷完成之后,調用的

merge標簽只能是根節點,include標簽不能是根節點。

布局優化

view的inflate的過程是深度遍歷,因此應該盡量減少viewTree的層次,可以考慮使用merge標簽

如果我們不知道view什么時候填充的時候,可以使用ViewStub標簽,什么時候用什么時候填充

include是提升復用的

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,739評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,634評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,653評論 0 377
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,063評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,835評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,235評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,315評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,459評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,000評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,819評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,004評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,560評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,257評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,676評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,937評論 1 288
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,717評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,003評論 2 374

推薦閱讀更多精彩內容

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