探索Android視圖加載器LayoutInflater

這次跟大家分享的是關(guān)于LayoutInflater的使用,在開發(fā)的過程中,LayoutInfalter經(jīng)常用于加載視圖,對,今天咱們來聊的就是,關(guān)于加載視圖的一些事兒,我記得之前一位曾共事過的一位同事問到我一個(gè)問題,activity是如何加載資源文件來顯示界面的,古話說得好,知其然不知其所以然,因此在寫這篇文章的時(shí)候我也做了不少的準(zhǔn)備,在這里我先引出幾個(gè)問題,然后我們通過問題在源碼中尋找答案。

1.如何獲取LayoutInflater?
2.如何使用LayoutInflater?為什么?
3.Activity是如何加載視圖的?
4.如何優(yōu)化我們的布局?

首先我們先看一下LayoutInflater是如何獲取的。

LayoutInflater inflater=LayoutInflater.from(context);

我們通過LayoutInflater.from(Context)獲取LayoutInflater,我們繼續(xù)進(jìn)入LayoutInflater.java探索一番。
LayoutInflater.java:

/**
 * 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;
}

在LayoutInflater里面,通過靜態(tài)方法from(Context),然后繼續(xù)調(diào)用Context中的方法getSystemService獲取LayoutInflater,我們往Context繼續(xù)看。

Context.java:

public abstract Object getSystemService(@ServiceName @NonNull String name);

大家會(huì)發(fā)現(xiàn),怎么點(diǎn)進(jìn)去這是個(gè)抽象方法,其實(shí)Context是一個(gè)抽象類,真正實(shí)現(xiàn)的是ContextImpl這個(gè)類,我們就繼續(xù)看ContextImpl:
ContextImpl.java:

@Override
public Object getSystemService(String name) {
    //繼續(xù)調(diào)用SystemServiceRegistry.getSystemService
    return SystemServiceRegistry.getSystemService(this, name);
}

SystemServiceRegistry.java:

/**
 * Gets a system service from a given context.
 */
public static Object getSystemService(ContextImpl ctx, String name) {
    //先獲取ServiceFetcher,在通過fetcher獲取LayoutInflate
    ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
    return fetcher != null ? fetcher.getService(ctx) : null;
}

SystemServiceRegistry這個(gè)類中的靜態(tài)方法getSystemService,通過SYSTEM_SERVICE_FETCHERS獲取ServiceFetcher,我們先看看SYSTEM_SERVICE_FETCHERS跟ServiceFetcher在SystemServiceRegistry中的定義。
SystemServiceRegistry.java:

//使用鍵值對來保存
private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
        new HashMap<String, ServiceFetcher<?>>();

/**
 * Base interface for classes that fetch services.
 * These objects must only be created during static initialization.
 */
static abstract interface ServiceFetcher<T> {
    //只有一條接口,通過context獲取服務(wù),先看一下其實(shí)現(xiàn)類
    T getService(ContextImpl ctx);
}

SYSTEM_SERVICE_FETCHERS在SystemServiceRegistry這個(gè)類中作為全局常量,通過鍵值對的方式用來保存ServiceFetcher,而ServiceFetcher又是什么?在源碼中,ServiceFetcher是一條接口,通過泛型T定義了getService(ContextImpl)來獲取服務(wù)對象。那么具體ServiceFetcher具體的實(shí)現(xiàn)在什么地方?在SystemServiceRegistry中,有一段這樣的代碼:
SystemServiceRegistry.java:

static {
    .....
    registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
        new CachedServiceFetcher<LayoutInflater>() {
    @Override
    public LayoutInflater createService(ContextImpl ctx) {
        return new PhoneLayoutInflater(ctx.getOuterContext());
    }});

......
}

在這個(gè)靜態(tài)代碼塊中,通過registerService進(jìn)行初始化注冊服務(wù)。我們先看看這個(gè)靜態(tài)方法。

/**
 * 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);
}

registerService這個(gè)一段函數(shù)的作用就是用來通過鍵值對的方式,保存服務(wù)對象,也就是說,SystemServiceRegistry會(huì)初始化的時(shí)候注冊各種服務(wù),而我們的也看到Context.LAYOUT_INFLATER_SERVICE作為key來獲取LayoutInfalter。

Context.java:

/**
 * 定義這個(gè)常量,用于獲取系統(tǒng)服務(wù)中的LayoutInflate
 * Use with {@link #getSystemService} to retrieve a
 * {@link android.view.LayoutInflater} for inflating layout resources in this
 * context.
 *
 * @see #getSystemService
 * @see android.view.LayoutInflater
 */
public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";

我們繼續(xù)看看ServiceFetcher的實(shí)現(xiàn)類:

/**
 * Override this class when the system service constructor needs a
 * ContextImpl and should be cached and retained by that context.
 */
static abstract class CachedServiceFetcher<T> implements ServiceFetcher<T> {
    private final int mCacheIndex;

    public CachedServiceFetcher() {
        mCacheIndex = sServiceCacheSize++;
    }

    @Override
    @SuppressWarnings("unchecked")
    public final T getService(ContextImpl ctx) {
        final Object[] cache = ctx.mServiceCache;
        synchronized (cache) {
            // Fetch or create the service.
            Object service = cache[mCacheIndex];
            if (service == null) {
                service = createService(ctx);
                cache[mCacheIndex] = service;
            }
            return (T)service;
        }
    }

    public abstract T createService(ContextImpl ctx);
}

CachedServiceFetcher的作用用于保存我們的泛型T,同時(shí)這個(gè)CachedServiceFetcher有一個(gè)抽象方法createService,createService這個(gè)方法用來創(chuàng)建這個(gè)服務(wù),因此使用這個(gè)類就必須重寫這個(gè)方法,我們繼續(xù)看回:

ServiceFetcher.java:

staic{
    registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
            new CachedServiceFetcher<LayoutInflater>() {
        @Override
        public LayoutInflater createService(ContextImpl ctx) {
            return new PhoneLayoutInflater(ctx.getOuterContext());
    }});
}

現(xiàn)在看回來這里,注冊服務(wù)不就是通過通過鍵值對的方式進(jìn)行保存這個(gè)對象,然而我們獲取到的LayoutInflater其實(shí)是PhoneLayoutInflater。PhoneLayoutInflater繼承于LayoutInfalter.

小結(jié):

我們獲取LayoutInflater對象,可以通過兩種方法獲?。?/p>

LayoutInflater inflater1=LayoutInflater.from(context);
LayoutInflater inflater2= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

context的實(shí)現(xiàn)類contextImpl,調(diào)用SystemServiceRegistry.getSystemService,通過鍵值對的方式獲取PhoneLayoutInflater對象,從中我們也看到,這種方式通過鍵值對的方式緩存起這個(gè)對象,避免創(chuàng)建過多的對象,這是也一種單例的設(shè)計(jì)模式。

現(xiàn)在咱們來看一下,我們是如何使用LayoutInflater來獲取View,我們先從一段小代碼看看。

我新建一個(gè)布局文件,my_btn.xml:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:text="我是一個(gè)按鈕">

</Button>

在布局文件中,我設(shè)置其layoutwidth與layout_height分別是填充屏幕。
在activity的content_main.xml布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="ffzxcom.mytest.toucheventapplication.MainActivity"
    tools:showIn="@layout/activity_main">


</RelativeLayout>

LayoutInflater.java:
方法一:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
    return inflate(resource, root, root != null);
}
 
 

方法二:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
    final Resources res = getContext().getResources();
    if (DEBUG) {
        Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                + Integer.toHexString(resource) + ")");
    }
    //通過資源加載器和資源Id,獲取xml解析器
    final XmlResourceParser parser = res.getLayout(resource);
    try {
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

我們從代碼中看到,無論是方法一,還是方法二,最終還是會(huì)調(diào)用方法二進(jìn)行加載,我們就從方法二的三個(gè)參數(shù),進(jìn)行分析一下。

@LayoutRes int resource 資源文件的Id
@Nullable ViewGroup root 根view,就是待加載view的父布局
boolean attachToRoot 是否加載到父布局中

從方法一看到,其實(shí)就是在調(diào)用方法二,只是方法一的第三個(gè)傳參利用root!=null進(jìn)行判斷而已,實(shí)際上最終還是調(diào)用方法二。

我們先利用代碼進(jìn)行分析一下:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mContainer = (RelativeLayout) findViewById(R.id.content_main);

    View view1 = LayoutInflater.from(this).inflate(R.layout.my_btn, null);
    View view2 = LayoutInflater.from(this).inflate(R.layout.my_btn, mContainer, false);
    View view3 = LayoutInflater.from(this).inflate(R.layout.my_btn, mContainer, true);
    View view4 = LayoutInflater.from(this).inflate(R.layout.my_btn, mContainer);

    Log.e("view1:", view1 + "");
    Log.e("view2:", view2 + "");
    Log.e("view3:", view3 + "");
    Log.e("view4:", view4 + "");
}

我們加載同一個(gè)布局文件my_btn.xml,獲取到view,然后分別輸出,觀察有什么不一樣:

view1:: android.support.v7.widget.AppCompatButton{27f4a822 VFED..C. ......I. 0,0-0,0}
view2:: android.support.v7.widget.AppCompatButton{14fb5dd2 VFED..C. ......I. 0,0-0,0}
view3:: android.widget.RelativeLayout{2a6bba10 V.E..... ......I. 0,0-0,0 #7f0c006f app:id/content_main}
view4:: android.widget.RelativeLayout{2a6bba10 V.E..... ......I. 0,0-0,0 #7f0c006f app:id/content_main}

問題來了,為什么我加載同一個(gè)布局,得到的view一個(gè)是Button,一個(gè)是RelativeLayout,我們每一個(gè)分析一下:

View1:
LayoutInflater.from(this).inflate(R.layout.my_btn, null);
我們看到,第二個(gè)參數(shù)root為空,也就是說實(shí)際上是調(diào)用方法二(root!=null):
LayoutInflater.from(this).inflate(R.layout.my_btn, null,false);
第三個(gè)參數(shù)attachToRoot 的意思是,是否把這個(gè)view添加到root里面,如果為false則不返回root,而是這個(gè)的本身,如果為true的話,就是返回添加view后的root.
因此,view1得到的是Button.

View2:
LayoutInflater.from(this).inflate(R.layout.my_btn, mContainer, false);
同上可得,第三個(gè)參數(shù)attachToRoot 為false.也就是不把這個(gè)view添加到root里面去
因此,返回的是view2,就是Button.

View3:
LayoutInflater.from(this).inflate(R.layout.my_btn, mContainer, true);
第三個(gè)參數(shù)為true,也就是意味待加載的view會(huì)附在root上,并且返回root.
因此,我們view3返回的是這個(gè)RelativeLayout,并且是添加button后的RelativeLayout.

View4:
LayoutInflater.from(this).inflate(R.layout.my_btn, mContainer);
根據(jù)方法一跟方法二的比較,root!=null.view4跟view3的加載是一樣的,同理返回的是RelativeLayout.

根據(jù)以上的結(jié)論我們繼續(xù)往下面探究,我們通過LayoutInflater.from(this).inflate(R.layout.my_btn, null)獲取到了button,再把這個(gè)Button添加到mContainer中。再觀察一下效果,注意,這個(gè)按鈕的布局寬高是占全屏的。

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:text="我是一個(gè)按鈕">

</Button>
 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mContainer = (RelativeLayout) findViewById(R.id.content_main);
    Button btn = (Button) LayoutInflater.from(this).inflate(R.layout.my_btn, null);
    mContainer.addView(btn);
}
無標(biāo)題.png

大家看到問題了嗎?為什么我在my_btn.xml中設(shè)置了button的布局寬高是全屏,怎么不起作用了?難道說在my_btn.xml中Button的layout_width和layout_height起不了作用?我們從源碼中看一下:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
    //獲取資源加載器
    final Resources res = getContext().getResources();
    if (DEBUG) {
        Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                + Integer.toHexString(resource) + ")");
    }
    //通過資源加載器和資源Id,獲取xml解析器
    final XmlResourceParser parser = res.getLayout(resource);
    try {
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

通過資源管理獲取xml解析器,繼續(xù)往下看:

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    synchronized (mConstructorArgs) {
        ......
        //保存?zhèn)鬟M(jìn)來的這個(gè)view
        View result = root;

        try {
            // Look for the root node.
            int type;
            //在這里找到root標(biāo)簽
            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!");
            }
            //獲取這個(gè)root標(biāo)簽的名字
            final String name = parser.getName();
             ......

            //判斷是否merge標(biāo)簽
            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");
                }
                //這里直接加載頁面,忽略merge標(biāo)簽,直接傳root進(jìn)rInflate進(jìn)行加載子view
                rInflate(parser, root, inflaterContext, attrs, false);
            } else {
                //通過標(biāo)簽來獲取view
                //先獲取加載資源文件中的根view
                final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                
                //布局參數(shù)          
                ViewGroup.LayoutParams params = null;
               
                //關(guān)鍵代碼A
                if (root != null) {
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        //temp設(shè)置布局參數(shù)
                        temp.setLayoutParams(params);
                    }
                }
                  ......
                //關(guān)鍵代碼B
                //在這里,先獲取到了temp,再把temp當(dāng)做root傳進(jìn)去rInflateChildren
                //進(jìn)行加載temp后面的子view
                rInflateChildren(parser, temp, attrs, true);
                  ......
               
                 //關(guān)鍵代碼C
                if (root != null && attachToRoot) {
                    //把view添加到root中并設(shè)置布局參數(shù)
                    root.addView(temp, params);
                }

                //關(guān)鍵代碼D
                if (root == null || !attachToRoot) {
                    result = temp;
                }
            }

        } catch (XmlPullParserException e) {
            ......
        } catch (Exception e) {
            ......
        } finally {
            ......
        }

        return result;
    }
}

在這一塊代碼中,先聲明一個(gè)變量result,這個(gè)result用來返回最終的結(jié)果,在我們的演示中,如果inflate(resource,root,isAttachRoot)中的root為空,那么布局參數(shù)params為空,并且根據(jù)關(guān)鍵代碼D可得,返回的result就是temp,也就是Button本身。因此在以上例子中,如果說root不為空的話,Button中聲明的layout_width與layout_height起到了作用。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mContainer = (RelativeLayout) findViewById(R.id.content_main);

    View view1 = LayoutInflater.from(this).inflate(R.layout.my_btn, mContainer,false);
    mContainer.addView(view1);
}
無標(biāo)題.png

注:如果通過LayoutInflater.from(this).inflate(R.layout.my_btn, mContainer)或者LayoutInflater.from(this).inflate(R.layout.my_btn, mContainer,true)加載視圖,不需要再額外的使用mContainer.addView(view),因?yàn)榉祷氐哪J(rèn)就是root本身,在關(guān)鍵代碼C中可看到:

if (root != null && attachToRoot) {
    root.addView(temp, params);
}
 

root會(huì)添加temp進(jìn)去,在代碼初始化的時(shí)候,result默認(rèn)就是root,我們不需要addView,在inflate中會(huì)幫我們操作,如果我們還要addView的話,就會(huì)拋出異常:
The specified child already has a parent. You must call removeView() on the child's parent first.

小結(jié):

如果LayoutInflater的inflate中,傳參root為空時(shí),加載視圖的根view布局寬高無效。反之根據(jù)關(guān)鍵代碼C與關(guān)鍵代碼A,分別對view進(jìn)行設(shè)置布局參數(shù)。

咱們來看一下activity是如何加載視圖,我們從這一段代碼開始:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

}

我們往setContentView繼續(xù)探索,找到Activity的setContentView()

/**
 * Set the activity content from a layout resource.  The resource will be
 * inflated, adding all top-level views to the activity.
 *
 * @param layoutResID Resource ID to be inflated.
 *
 * @see #setContentView(android.view.View)
 * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
 */
public void setContentView(@LayoutRes int layoutResID) {
    //獲取窗口,設(shè)置contentView
    getWindow().setContentView(layoutResID);
    initWindowDecorActionBar();
}

getWindow()實(shí)際上是獲取window對象,但Window類是抽象類,具體的實(shí)現(xiàn)是PhoneWindow,我們往這個(gè)類看看:
PhoneWindow.java:

@Override
public void setContentView(int layoutResID) {
    //判斷mContentParent是否為空,如果為空,創(chuàng)建
    if (mContentParent == null) {
        installDecor();
    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        // 清空mContentParent 所有子view       
        mContentParent.removeAllViews();
    }

    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
       ……
    } else {
        //通過layoutInflate加載視圖         
        mLayoutInflater.inflate(layoutResID, mContentParent);
    }
    ……
}

activity加載視圖,最后還是通過LayoutInflater進(jìn)行加載視圖,activity的界面結(jié)構(gòu)如下:

無標(biāo)題.png

我們的mContentView就是ContentView,因此通過LayoutInflater加載視圖進(jìn)入ContentView。而root就是mContentView,因此我們在Activity不需要自己addView().

總結(jié):
知其然不知其所以然,這對于LayoutInflater描述再合適不過了,文章中本來還涉及到了關(guān)于如何使用LayoutInflater中遍歷view,代碼太長就不一一展示,而且在inflate中我們可以看到,通過使用merge標(biāo)簽,可以減少view的層級(jí),直接把merge標(biāo)簽內(nèi)的子view直接添加到rootview中,因此布局優(yōu)化能提高視圖加載的性能,提高效率。還有獲取LayoutInflater的方式,通過鍵值對進(jìn)行緩存LayoutInflater,這是在android中單例設(shè)計(jì)的一種體驗(yàn)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容