Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

追進源碼:Android View 的背景圖究竟何時被載入

編輯:Android 資訊

做 Android 介面,最高頻的操作大概就是排版和設背景圖。但我們很少去追問:這張圖到底是什麼時候、經過哪些環節被載入的?搞清這條鏈路有兩個實際好處——效能優化時知道該往哪下手,做換膚時也更有底氣。

設背景的方式通常兩種:XML 裡寫 android:background 交給系統,或手動解碼成 Bitmap 再塞給 View。本文關心的是第一種:系統在哪裡、怎麼幫我們完成載入。起點可以選 Activity.setContentView(),也可以直接從 LayoutInflater.inflate() 開始。

inflate 主流程

不論走 Activity 還是 LayoutInflater,最終都會匯流到 inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)。XML 如何解析這裡先跳過,只看主幹:

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
    synchronized (mConstructorArgs) {
        final AttributeSet attrs = Xml.asAttributeSet(parser);
        Context lastContext = (Context) mConstructorArgs[0];
        mConstructorArgs[0] = mContext;
        View result = root;
        try {
            // 找到根節點
            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG
                    && type != XmlPullParser.END_DOCUMENT) {
                // 空迴圈
            }
            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, attrs, false);
            } else {
                // temp 是 XML 裡找到的根 View
                View temp = createViewFromTag(root, name, attrs);

                ViewGroup.LayoutParams params = null;
                if (root != null) {
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        temp.setLayoutParams(params);
                    }
                }

                // 遞迴載入所有子 View
                rInflate(parser, temp, attrs, true);

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

                if (root == null || !attachToRoot) {
                    result = temp;
                }
            }
        } catch (XmlPullParserException e) {
            throw new InflateException(e.getMessage());
        } catch (IOException e) {
            throw new InflateException(
                    parser.getPositionDescription() + ": " + e.getMessage());
        } finally {
            mConstructorArgs[0] = lastContext;
            mConstructorArgs[1] = null;
        }
        return result;
    }
}

邏輯其實很直白:解析 XML,為每個節點建立對應 View,套用 LayoutParams,掛到父容器上。真正關鍵的只有一行:

temp = createViewFromTag(root, name, attrs);

createViewFromTag:Factory 的介入點

View createViewFromTag(View parent, String name, AttributeSet attrs) {
    if (name.equals("view")) {
        name = attrs.getAttributeValue(null, "class");
    }
    try {
        View view;
        if (mFactory2 != null) {
            view = mFactory2.onCreateView(parent, name, mContext, attrs);
        } else if (mFactory != null) {
            view = mFactory.onCreateView(name, mContext, attrs);
        } else {
            view = null;
        }
        if (view == null && mPrivateFactory != null) {
            view = mPrivateFactory.onCreateView(parent, name, mContext, attrs);
        }
        if (view == null) {
            if (-1 == name.indexOf('.')) {
                view = onCreateView(parent, name, attrs);
            } else {
                view = createView(name, null, attrs);
            }
        }
        return view;
    } catch (InflateException e) {
        throw e;
    } catch (Exception e) {
        throw new InflateException(attrs.getPositionDescription()
                + ": Error inflating class " + name);
    }
}

這段程式碼藏著一個很有用的擴展點:幾個 Factory。如果我們自訂了一個 Factory,那麼 View 會優先交給它建立,系統預設的 Factory 就沒機會插手。

Factory 必須趕在資源載入前設定好,也就是說要寫在 onCreate() 裡、setContentView() 之前:

getLayoutInflater().setFactory(factory);

接著看分支判斷:

if (-1 == name.indexOf('.')) {
    view = onCreateView(parent, name, attrs);
} else {
    view = createView(name, null, attrs);
}

名字裡沒點號的,是系統內建 View——因為 XML 裡通常懶得寫 android.view. 前綴;帶點號的則是使用者自訂 View。先看系統這一邊:

protected View onCreateView(String name, AttributeSet attrs)
        throws ClassNotFoundException {
    return createView(name, "android.view.", attrs);
}

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 {
        if (constructor == null) {
            // 快取裡沒有,載入類別並取出建構子
            clazz = mContext.getClassLoader()
                    .loadClass(prefix != null ? (prefix + name) : name)
                    .asSubclass(View.class);
            if (mFilter != null && clazz != null) {
                if (!mFilter.onLoadClass(clazz)) {
                    failNotAllowed(name, prefix, attrs);
                }
            }
            constructor = clazz.getConstructor(mConstructorSignature);
            sConstructorMap.put(name, constructor);
        } else {
            // 命中快取,只需在有 filter 時檢查一次權限
            if (mFilter != null) {
                Boolean allowedState = mFilterMap.get(name);
                if (allowedState == null) {
                    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) {
            // ViewStub 後續 inflate 時仍用當前的 LayoutInflater
            ((ViewStub) view).setLayoutInflater(this);
        }
        return view;
    } catch (NoSuchMethodException e) {
        throw new InflateException(attrs.getPositionDescription()
                + ": Error inflating class " + name);
    } catch (ClassCastException e) {
        throw new InflateException(attrs.getPositionDescription()
                + ": Class is not a View " + name);
    } catch (ClassNotFoundException e) {
        throw e;
    } catch (Exception e) {
        throw new InflateException(attrs.getPositionDescription()
                + ": Error inflating class " + name);
    }
}

這裡有兩個值得記住的細節。第一,系統會快取建構子(sConstructorMap),因為像 TextView 這種常用元件會被反覆建立,反射一次的成本不低。第二,傳給建構子的 mConstructorArgs 是長度為 2 的陣列:

final Object[] mConstructorArgs = new Object[2];

也就是說,系統呼叫的是 View(Context, AttributeSet) 這個兩參數建構子。我們直接看最基礎的 View:

public View(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public View(Context context, AttributeSet attrs, int defStyle) {
    this(context);
    TypedArray a = context.obtainStyledAttributes(
            attrs, com.android.internal.R.styleable.View, defStyle, 0);

    Drawable background = null;
    int leftPadding = -1, topPadding = -1, rightPadding = -1, bottomPadding = -1;
    // ... 其他屬性暫存變數省略

    final int N = a.getIndexCount();
    for (int i = 0; i < N; i++) {
        int attr = a.getIndex(i);
        switch (attr) {
            case com.android.internal.R.styleable.View_background:
                background = a.getDrawable(attr);
                break;
            case com.android.internal.R.styleable.View_padding:
                int padding = a.getDimensionPixelSize(attr, -1);
                mUserPaddingLeftInitial = padding;
                mUserPaddingRightInitial = padding;
                break;
            // 其餘屬性省略
        }
    }
}

這個建構子做的事就是遍歷 AttributeSet,把 XML 上的屬性一個個套到 View 上。我們關心的背景在這一行:

background = a.getDrawable(attr);

TypedArray 到 Resources

public Drawable getDrawable(int index) {
    final TypedValue value = mValue;
    if (getValueAt(index * AssetManager.STYLE_NUM_ENTRIES, value)) {
        return mResources.loadDrawable(value, value.resourceId);
    }
    return null;
}

於是線索交到了 Resources.loadDrawable():

Drawable loadDrawable(TypedValue value, int id) throws NotFoundException {
    boolean isColorDrawable = false;
    if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
            && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
        isColorDrawable = true;
    }

    // 1. 先查應用級快取
    final long key = isColorDrawable ? value.data
            : (((long) value.assetCookie) << 32) | value.data;
    Drawable dr = getCachedDrawable(
            isColorDrawable ? mColorDrawableCache : mDrawableCache, key);
    if (dr != null) {
        return dr;
    }

    // 2. 再查預載入快取,命中則用 ConstantState 複製一份
    Drawable.ConstantState cs = isColorDrawable
            ? sPreloadedColorDrawables.get(key)
            : (sPreloadedDensity == mConfiguration.densityDpi
                    ? sPreloadedDrawables.get(key) : null);
    if (cs != null) {
        dr = cs.newDrawable(this);
    } else {
        if (isColorDrawable) {
            dr = new ColorDrawable(value.data);
        }
        if (dr == null) {
            if (value.string == null) {
                throw new NotFoundException(
                        "Resource is not a Drawable (color or path): " + value);
            }
            String file = value.string.toString();

            if (file.endsWith(".xml")) {
                // 3a. XML 型別的 drawable(shape / selector / layer-list ...)
                XmlResourceParser rp = loadXmlResourceParser(
                        file, id, value.assetCookie, "drawable");
                dr = Drawable.createFromXml(this, rp);
                rp.close();
            } else {
                // 3b. 位圖等資源檔
                InputStream is = mAssets.openNonAsset(
                        value.assetCookie, file, AssetManager.ACCESS_STREAMING);
                dr = Drawable.createFromResourceStream(this, value, is, file, null);
                is.close();
            }
        }
    }

    // 4. 依是否處於預載入階段,決定寫入全域預載入表或應用快取
    if (dr != null) {
        dr.setChangingConfigurations(value.changingConfigurations);
        cs = dr.getConstantState();
        if (cs != null) {
            if (mPreloading) {
                if (verifyPreloadConfig(value, "drawable")) {
                    if (isColorDrawable) {
                        sPreloadedColorDrawables.put(key, cs);
                    } else {
                        sPreloadedDrawables.put(key, cs);
                    }
                }
            } else {
                synchronized (mTmpValue) {
                    if (isColorDrawable) {
                        mColorDrawableCache.put(key,
                                new WeakReference<Drawable.ConstantState>(cs));
                    } else {
                        mDrawableCache.put(key,
                                new WeakReference<Drawable.ConstantState>(cs));
                    }
                }
            }
        }
    }
    return dr;
}

這就是背景載入的全貌。策略可以概括為四層:純色直接造 ColorDrawable;其餘先查應用快取,再查全域預載入表(用 ConstantState 複製新例,避免多處共用同一 Drawable 而互相干擾);都沒有才真正讀檔,XML 走 Drawable.createFromXml(),圖片走串流解碼;最後依階段決定要不要寫回快取。

把整條鏈路串起來:Activity.setContentView() → LayoutInflater.inflate() → createViewFromTag() → createView() 反射建立 View → View 建構子遍歷屬性 → TypedArray.getDrawable() → Resources.loadDrawable()。所以精確地說,資源載入發生在每個被初始化的 View 的建構子裡,而不是某個統一的入口。

理解了這一點,幾個實務判斷就有了依據:為什麼大量引用同一張圖不會重複解碼(ConstantState 複用);為什麼換膚要清快取(mDrawableCache 是應用級的);以及為什麼過大的背景圖會顯著拖慢首屏——它是在 View 建構階段同步解碼的。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved