我們前面說過APK可以分爲代碼與資源兩部分,那麼在加載APK時也會涉及代碼的加載和資源的加載,代碼的加載事實上對應的就是Android應用進程的創建流程,關於這一塊的內容我們在文章01Android進程框架:進程的創建、啓動與調度流程已經分析過,本篇文章 我們着重來分析資源的加載流程。
我們知道在代碼中我們通常會通過getResource()去獲取Resources對象,Resource對象是應用進程內的一個全局對象,它用來訪問應用的資源。除了Resources對象我們還可以通過getAsset()獲取 AssetManger來讀取指定文件路徑下的文件。Resource與AssetManger這對兄弟就構造了資源訪問框架的基礎。
那麼AssetManager對象與Resources對象在哪裏創建的呢?🤔
3.1 AssetManager的創建流程
我們知道每個啓動的應用都需要先創建一個應用上下文Context,Context的實際實現類是ContextImpl,ContextImpl在創建的時候創建了Resources對象和AssetManager對象。
AssetManager對象創建序列圖如下所示:
我們可以發現在整個流程AssetManager在Java和C++層都有一個實現,那麼它們倆有什麼關係呢?🤔
事實上實際的功能都是由C++層的AssetManag來完成的。每個Java層的AssetManager對象都一個long型的成員變量mObject,用來保存C++層 AssetManager對象的地址,通過這個變量將Java層的AssetManager對象與C++層的AssetManager對象關聯起來。
public final class AssetManager implements AutoCloseable {
// 通過這個變量將Java層的AssetManager對象與C++層的AssetManager對象關聯起來。
private long mObject;
}
從上述序列圖中我們可以看出,最終調用Asset的構造函數來創建Asset對象,如下所示:
public final class AssetManager implements AutoCloseable {
public AssetManager() {
synchronized (this) {
if (DEBUG_REFS) {
mNumRefs = 0;
incRefsLocked(this.hashCode());
}
init(false);
if (localLOGV) Log.v(TAG, "New asset manager: " + this);
//創建系統的AssetManager
ensureSystemAssets();
}
}
private static void ensureSystemAssets() {
synchronized (sSync) {
if (sSystem == null) {
AssetManager system = new AssetManager(true);
system.makeStringBlocks(null);
sSystem = system;
}
}
}
private AssetManager(boolean isSystem) {
if (DEBUG_REFS) {
synchronized (this) {
mNumRefs = 0;
incRefsLocked(this.hashCode());
}
}
init(true);
if (localLOGV) Log.v(TAG, "New asset manager: " + this);
}
private native final void init(boolean isSystem);
}
可以看到構造函數會先調用native方法init()去構造初始化AssetManager對象,可以發現它還調用了ensureSystemAssets()方法去創建系統AssetManager,爲什麼還會有個系統AssetManager呢?🤔
這是因爲Android應用程序不僅要訪問自己的資源,還需要訪問系統的資源,系統的資源放在/system/framework/framework-res.apk文件中,它在應用進程中是通過一個單獨的Resources對象(Resources.sSystem) 和一個單獨的AssetManger(AssetManager.sSystem)對象來管理的。
我們接着來看native方法init()的實現,它實際上是調用android_util_AssetManager.cpp類的android_content_AssetManager_init()方法,如下所示;
👉 android_util_AssetManager.cpp
static void android_content_AssetManager_init(JNIEnv* env, jobject clazz, jboolean isSystem)
{
if (isSystem) {
verifySystemIdmaps();
}
//構建AssetManager對象
AssetManager* am = new AssetManager();
if (am == NULL) {
jniThrowException(env, "java/lang/OutOfMemoryError", "");
return;
}
//添加默認的資源路徑,也就是系統資源的路徑
am->addDefaultAssets();
ALOGV("Created AssetManager %p for Java object %p\n", am, clazz);
env->SetLongField(clazz, gAssetManagerOffsets.mObject, reinterpret_cast<jlong>(am));
}
我們接着來看看AssetManger.cpp的ddDefaultAssets()方法。
static const char* kSystemAssets = "framework/framework-res.apk";
bool AssetManager::addDefaultAssets()
{
const char* root = getenv("ANDROID_ROOT");
LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
String8 path(root);
path.appendPath(kSystemAssets);
return addAssetPath(path, NULL, false /* appAsLib */, true /* isSystemAsset */);
}
ANDROID_ROOT指的就是/sysetm目錄,全局變量kSystemAssets指向的是"framework/framework-res.apk",所以拼接以後就是我們前面說的系統資源的存放目錄"/system/framework/framework-res.apk"
拼接好path後作爲參數傳入addAssetPath()方法,注意Java層的addAssetPath()方法實際調用的也是底層的此方法,如下所示:
static const char* kAppZipName = NULL; //"classes.jar";
bool AssetManager::addAssetPath(
const String8& path, int32_t* cookie, bool appAsLib, bool isSystemAsset)
{
AutoMutex _l(mLock);
asset_path ap;
String8 realPath(path);
//kAppZipName如果不爲NULL,一般將會被設置爲classes.jar
if (kAppZipName) {
realPath.appendPath(kAppZipName);
}
//檢查傳入的path是一個文件還是一個目錄,兩者都不是的時候直接返回
ap.type = ::getFileType(realPath.string());
if (ap.type == kFileTypeRegular) {
ap.path = realPath;
} else {
ap.path = path;
ap.type = ::getFileType(path.string());
if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
ALOGW("Asset path %s is neither a directory nor file (type=%d).",
path.string(), (int)ap.type);
return false;
}
}
//資源路徑mAssetPaths是否已經添加過參數path描述的一個APK的文件路徑,如果
//已經添加過,則不再往下處理。直接將path保存在輸出參數cookie中
for (size_t i=0; i<mAssetPaths.size(); i++) {
if (mAssetPaths[i].path == ap.path) {
if (cookie) {
*cookie = static_cast<int32_t>(i+1);
}
return true;
}
}
ALOGV("In %p Asset %s path: %s", this,
ap.type == kFileTypeDirectory ? "dir" : "zip", ap.path.string());
ap.isSystemAsset = isSystemAsset;
//path所描述的APK資源路徑沒有被添加過,則添加到mAssetPaths中。
mAssetPaths.add(ap);
//...
return true;
該方法的實現也很簡單,就是把path描述的APK資源路徑加入到資源目錄數組mAssetsPath中去,mAssetsPath是AssetManger.cpp的成員變量,AssetManger.cpp有三個 比較重要的成員變量:
- mAssetsPath:資源存放目錄。
- mResources:資源索引表。
- mConfig:設備的本地配置信息,包括設備大小,國家地區、語音等配置信息。
有了這些變量AssetManger就可以正常的工作了。AssetManger對象也就創建完成了。
ResroucesManager的createResroucesImpl()方法會先調用createAssetManager()方法創建AssetManger對象,然後再調用ResourcesImpl的構造方法創建ResourcesImpl對象。
3.1 Resources的創建流程
Resources對象的創建序列圖如下所示:
ResourcesImpl的構造方法如下所示:
public class ResourcesImpl {
public ResourcesImpl(@NonNull AssetManager assets, @Nullable DisplayMetrics metrics,
@Nullable Configuration config, @NonNull DisplayAdjustments displayAdjustments) {
mAssets = assets;
mMetrics.setToDefaults();
mDisplayAdjustments = displayAdjustments;
updateConfiguration(config, metrics, displayAdjustments.getCompatibilityInfo());
mAssets.ensureStringBlocks();
}
}
在這個方法裏有兩個重要的函數:
- updateConfiguration(config, metrics, displayAdjustments.getCompatibilityInfo()):首先是根據參數config和metrics來更新設備的當前配置信息,例如,屏幕大小和密碼、國家地區和語言、鍵盤 配置情況等,接着再調用成員變量mAssets所指向的一個Java層的AssetManager對象的成員函數setConfiguration來將這些配置信息設置到與之關聯的C++層的AssetManger。
- ensureStringBlocks():讀取
我們重點來看看ensureStringBlocks()的實現。
public final class AssetManager implements AutoCloseable {
@NonNull
final StringBlock[] ensureStringBlocks() {
synchronized (this) {
if (mStringBlocks == null) {
//讀取字符串資源池,sSystem.mStringBlocks表示系統資源索引表的字符串常量池
//前面我們已經創建的了系統資源的AssetManger sSystem,所以系統資源字符串資源池已經讀取完畢。
makeStringBlocks(sSystem.mStringBlocks);
}
return mStringBlocks;
}
}
//seed表示是否要將系統資源索引表裏的字符串資源池也一起拷貝出來
/*package*/ final void makeStringBlocks(StringBlock[] seed) {
//系統資源索引表個數
final int seedNum = (seed != null) ? seed.length : 0;
//總的資源索引表個數
final int num = getStringBlockCount();
mStringBlocks = new StringBlock[num];
if (localLOGV) Log.v(TAG, "Making string blocks for " + this
+ ": " + num);
for (int i=0; i<num; i++) {
if (i < seedNum) {
//系統預加載資源的時候,已經解析過framework-res.apk中的resources.arsc
mStringBlocks[i] = seed[i];
} else {
//調用getNativeStringBlock(i)方法讀取字符串資源池
mStringBlocks[i] = new StringBlock(getNativeStringBlock(i), true);
}
}
}
private native final int getStringBlockCount();
private native final long getNativeStringBlock(int block);
}
首先解釋一下什麼是StringBlocks,StringBlocks描述的是一個字符串資源池,Android裏每一個資源索引表resources.arsc都包含一個字符串資源池。 getStringBlockCount() 方法返回的也就是這種資源池的個數。
上面我們已經說了resources.arsc的文件格式,接下來就會調用native方法getNativeStringBlock()去解析resources.arsc文件的內容,獲取字符串 常量池,getNativeStringBlock()方法實際上就是將每一個資源包裏面的resources.arsc的數據項值的字符串資源池數據塊讀取出來,並封裝在C++層的StringPool對象中,然後Java層的makeStringBlocks()方法 再將該StringPool對象封裝成Java層的StringBlock中。
關於C++層的具體實現,可以參考羅哥的這兩篇博客:
如此,AssetManager和Resources對象的創建流程便分析完了,這兩個對象構成了Android應用程序資源管理器的核心基礎,資源的加載就是藉由這兩個對象來完成的。
3.3 資源的查找與解析流程
前面我們分析了AssetManager和Resources對象的創建流程,AssetManager根據文件名來查找資源,Resouces根據資源ID查找資源,如果資源ID對應的是個文件,那麼會Resouces先根據資源ID查找 出文件名,AssetManger再根據文件名查找出具體的資源。
整個流程還是比較簡單的,我們以layout.xml文件的查找流程爲例來說明一下,具體序列圖如下所示:
我們先來看看總的調度方法inflate(),這個也是我們最常用的
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
這個方法有三個參數:
int resource:佈局ID,也就是要解析的xml佈局文件,boolean attachToRoot表示是否要添加到父佈局root中去。這裏面還有個關鍵的參數root。它用來表示根佈局,這個就很常見的,我們在用 這個方法的時候,有時候給root賦值了,有時候直接給了null(給null的時候IDE會有警告提示),這個root到底有什麼作用呢?🤔
它主要有兩個方面的作用:
- 當attachToRoot == true且root != null時,新解析出來的View會被add到root中去,然後將root作爲結果返回。
- 當attachToRoot == false且root != null時,新解析的View會直接作爲結果返回,而且root會爲新解析的View生成LayoutParams並設置到該View中去。
- 當attachToRoot == false且root == null時,新解析的View會直接作爲結果返回。
注意第二條和第三條是由區別的,你可以去寫個例子試一下,當root爲null時,新解析出來的View沒有LayoutParams參數,這時候你設置的layout_width和layout_height是不生效的。
說到這裏,有人可能有疑問了,Activity裏的佈局應該也是LayoutInflater加載的,我也沒做什麼處理,但是我設置的layout_width和layout_heigh參數都是可以生效的,這是爲什麼?🤔
這是因爲Activity內部做了處理,我們知道Activity的setContentView()方法,實際上調用的PhoneWindow的setContentView()方法。它調用的時候將Activity的頂級DecorView(FrameLayout) 作爲root傳了進去,mLayoutInflater.inflate(layoutResID, mContentParent)實際調用的是inflate(resource, root, root != null),所以在調用Activity的setContentView()方法時 可以將解析出的View添加到頂級DecorView中,我們設置的layout_width和layout_height參數也可以生效。
具體代碼如下:
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
瞭解了inflate()方法各個參數的含義,我們正式來分析它的實現。
public abstract class LayoutInflater {
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) + ")");
}
//獲取xml資源解析器XmlResourceParser
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);//解析View
} finally {
parser.close();
}
}
}
可以發現在該方法裏,主要完成了兩件事情:
- 獲取xml資源解析器XmlResourceParser。
- 解析View
我們先來看看XmlResourceParser是如何獲取的。
從上面的序列圖可以看出,調用了Resources的getLayout(resource)去獲取對應的XmlResourceParser。getLayout(resource)又去調用了Resources的loadXmlResourceParser() 方法來完成XmlResourceParser的加載,如下所示:
public class Resources {
XmlResourceParser loadXmlResourceParser(@AnyRes int id, @NonNull String type)
throws NotFoundException {
final TypedValue value = obtainTempTypedValue();
try {
final ResourcesImpl impl = mResourcesImpl;
//1. 獲取xml佈局資源,並保存在TypedValue中。
impl.getValue(id, value, true);
if (value.type == TypedValue.TYPE_STRING) {
//2. 加載對應的loadXmlResourceParser解析器。
return impl.loadXmlResourceParser(value.string.toString(), id,
value.assetCookie, type);
}
throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
+ " type #0x" + Integer.toHexString(value.type) + " is not valid");
} finally {
releaseTempTypedValue(value);
}
}
}
可以發現這個方法又被分成了兩步:
- 獲取xml佈局資源,並保存在TypedValue中。
- 加載對應的loadXmlResourceParser解析器。
從上面的序列圖可以看出,資源的獲取涉及到resources.arsc的解析過程,這個我們已經在Resources的創建流程簡單聊過,這裏就不再贅述。通過 getValue()方法獲取到xml資源以後,就會調用ResourcesImpl的loadXmlResourceParser()方法對該佈局資源進行解析,以便得到一個UI佈局視圖。
我們來看看它的實現。
3.3.1 獲取XmlResourceParser
public class ResourcesImpl {
XmlResourceParser loadXmlResourceParser(@NonNull String file, @AnyRes int id, int assetCookie,
@NonNull String type)
throws NotFoundException {
if (id != 0) {
try {
synchronized (mCachedXmlBlocks) {
//... 從緩存中查找xml資源
// Not in the cache, create a new block and put it at
// the next slot in the cache.
final XmlBlock block = mAssets.openXmlBlockAsset(assetCookie, file);
if (block != null) {
final int pos = (mLastCachedXmlBlockIndex + 1) % num;
mLastCachedXmlBlockIndex = pos;
final XmlBlock oldBlock = cachedXmlBlocks[pos];
if (oldBlock != null) {
oldBlock.close();
}
cachedXmlBlockCookies[pos] = assetCookie;
cachedXmlBlockFiles[pos] = file;
cachedXmlBlocks[pos] = block;
return block.newParser();
}
}
} catch (Exception e) {
final NotFoundException rnf = new NotFoundException("File " + file
+ " from xml type " + type + " resource ID #0x" + Integer.toHexString(id));
rnf.initCause(e);
throw rnf;
}
}
throw new NotFoundException("File " + file + " from xml type " + type + " resource ID #0x"
+ Integer.toHexString(id));
}
}
我們先來看看這個方法的四個形參:
- String file:xml文件的路徑
- int id:xml文件的資源ID
- int assetCookie:xml文件的資源緩存
- String type:資源類型
ResourcesImpl會緩存最近解析的4個xml資源,如果不在緩存裏則調用AssetManger的openXmlBlockAsset()方法創建一個XmlBlock。XmlBlock是已編譯的xml文件的一個包裝類。
AssetManger的openXmlBlockAsset()方法的實現如下所示:
public final class AssetManager implements AutoCloseable {
/*package*/ final XmlBlock openXmlBlockAsset(int cookie, String fileName)
throws IOException {
synchronized (this) {
//...
long xmlBlock = openXmlAssetNative(cookie, fileName);
if (xmlBlock != 0) {
XmlBlock res = new XmlBlock(this, xmlBlock);
incRefsLocked(res.hashCode());
return res;
}
}
//...
}
}
可以看出該方法會調用native方法openXmlAssetNative()去代開fileName指定的xml文件,成功打開該文件後,會得到C++層的ResXMLTree對象的地址xmlBlock,然後將xmlBlock封裝進 XmlBlock中返回給調用者。ResXMLTreed對象會存放打開後xml資源的內容。
上述序列圖裏的AssetManger.cpp的方法的具體實現也就是一個打開資源文件的過程,資源文件一般存放在APK中,APK是一個zip包,所以最終會調用openAssetFromZipLocked()方法打開xml文件。
XmlBlock封裝完成後,會調用XmlBlock對象的newParser()方法去構建一個XmlResourceParser對象,實現如下所示:
final class XmlBlock {
public XmlResourceParser newParser() {
synchronized (this) {
//mNative指向的是C++層的ResXMLTree對象的地址
if (mNative != 0) {
return new Parser(nativeCreateParseState(mNative), this);
}
return null;
}
}
private static final native long nativeCreateParseState(long obj);
}
mNative指向的是C++層的ResXMLTree對象的地址,native方法nativeCreateParseState()根據這個地址找到ResXMLTree對象,利用ResXMLTree對象對象構建一個ResXMLParser對象,並將ResXMLParser對象 的地址封裝進Java層的Parser對象中,構建一個Parser對象。所以他們的對應關係如下所示:
- XmlBlock <--> ResXMLTree
- Parser <--> ResXMLParser
就是建立了Java層與C++層的對應關係,實際的實現還是由C++層完成。
等獲取了XmlResourceParser對象以後就可以調用inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) 方法進行View的解析了,在解析View時 ,會先去調用rInflate()方法解析View樹,然後再調用createViewFromTag()方法創建具體的View,我們來詳細的看一看。
3.3.2 解析View樹
- 解析merge標籤,rInflate()方法會將merge下面的所有子View直接添加到根容器中,這裏我們也理解了爲什麼merge標籤可以達到簡化佈局的效果。
- 不是merge標籤那麼直接調用createViewFromTag()方法解析成佈局中的視圖,這裏的參數name就是要解析視圖的類型,例如:ImageView。
- 調用generateLayoutParams()f方法生成佈局參數,如果attachToRoot爲false,即不添加到根容器裏,爲View設置佈局參數。
- 調用rInflateChildren()方法解析當前View下面的所有子View。
- 如果根容器不爲空,且attachToRoot爲true,則將解析出來的View添加到根容器中,如果根佈局爲空或者attachToRoot爲false,那麼解析出來的額View就是返回結果。返回解析出來的結果。
接下來,我們分別看下View樹解析以及View的解析。
public abstract class LayoutInflater {
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對象
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
//存儲根視圖
View result = root;
try {
// 獲取根元素
int type;
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!");
}
final String name = parser.getName();
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
//1. 解析merge標籤,rInflate()方法會將merge下面的所有子View直接添加到根容器中,這裏
//我們也理解了爲什麼merge標籤可以達到簡化佈局的效果。
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, inflaterContext, attrs, false);
} else {
//2. 不是merge標籤那麼直接調用createViewFromTag()方法解析成佈局中的視圖,這裏的參數name就是要解析視圖的類型,例如:ImageView
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
//3. 調用generateLayoutParams()f方法生成佈局參數,如果attachToRoot爲false,即不添加到根容器裏,爲View設置佈局參數
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
//4. 調用rInflateChildren()方法解析當前View下面的所有子View
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
//如果根容器不爲空,且attachToRoot爲true,則將解析出來的View添加到根容器中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
//如果根佈局爲空或者attachToRoot爲false,那麼解析出來的額View就是返回結果
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) {
final InflateException ie = new InflateException(parser.getPositionDescription()
+ ": " + e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
}
上面我們已經提到View樹的解析是有rInflate()方法來完成的,我們接着來看看View樹是如何被解析的。
public abstract class LayoutInflater {
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
//1. 獲取樹的深度,執行深度優先遍歷
final int depth = parser.getDepth();
int type;
//2. 逐個進行元素解析
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)) {
//3. 解析添加ad:focusable="true"的元素,並獲取View焦點。
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {
//4. 解析View的tag。
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
//5. 解析include標籤,注意include標籤不能作爲根元素。
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
//merge標籤必須爲根元素
throw new InflateException("<merge /> must be the root element");
} else {
//6. 根據元素名進行解析,生成View。
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
//7. 遞歸調用解析該View裏的所有子View,也是深度優先遍歷,rInflateChildren內部調用的也是rInflate()方
//法,只是傳入了新的parent View
rInflateChildren(parser, view, attrs, true);
//8. 將解析出來的View添加到它的父View中。
viewGroup.addView(view, params);
}
}
if (finishInflate) {
//9. 回調根容器的onFinishInflate()方法,這個方法我們應該很熟悉。
parent.onFinishInflate();
}
}
//rInflateChildren內部調用的也是rInflate()方法,只是傳入了新的parent View
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
}
上述方法描述了整個View樹的解析流程,我們來概括一下:
- 獲取樹的深度,執行深度優先遍歷.
- 逐個進行元素解析。
- 解析添加ad:focusable="true"的元素,並獲取View焦點。
- 解析View的tag。
- 解析include標籤,注意include標籤不能作爲根元素,而merge必須作爲根元素。
- 根據元素名進行解析,生成View。
- 遞歸調用解析該View裏的所有子View,也是深度優先遍歷,rInflateChildren內部調用的也是rInflate()方法,只是傳入了新的parent View。
- 將解析出來的View添加到它的父View中。
- 回調根容器的onFinishInflate()方法,這個方法我們應該很熟悉。
你可以看到,負責解析單個View的正是createViewFromTag()方法,我們再來分析下這個方法。
3.3.3 創建View
public abstract class LayoutInflater {
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
//1. 解析view標籤。注意是小寫view,這個不太常用,下面會說。
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
//2. 如果標籤與主題相關,則需要將context與themeResId包裹成ContextThemeWrapper。
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();
}
//3. BlinkLayout是一種會閃爍的佈局,被包裹的內容會一直閃爍,像QQ消息那樣。
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
View view;
//4. 用戶可以設置LayoutInflater的Factory來進行View的解析,但是默認情況下
//這些Factory都是爲空的。
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
//5. 默認情況下沒有Factory,而是通過onCreateView()方法對內置View進行解析,createView()
//方法進行自定義View的解析。
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
//這裏有個小技巧,因爲我們在使用自定義View的時候是需要在xml指定全路徑的,例如:
//com.guoxiaoxing.CustomView,那麼這裏就有個.了,可以利用這一點判定是內置View
//還是自定義View,Google的工程師很機智的。😎
if (-1 == name.indexOf('.')) {
//內置View解析
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;
}
}
}
單個View的解析流程也很簡單,我們來梳理一下:
- 解析View標籤。
- 如果標籤與主題相關,則需要將context與themeResId包裹成ContextThemeWrapper。
- BlinkLayout是一種會閃爍的佈局,被包裹的內容會一直閃爍,像QQ消息那樣。
- 用戶可以設置LayoutInflater的Factory來進行View的解析,但是默認情況下這些Factory都是爲空的。
- 默認情況下沒有Factory,而是通過onCreateView()方法對內置View進行解析,createView()方法進行自定義View的解析。這裏有個小技巧,因爲 我們在使用自定義View的時候是需要在xml指定全路徑的,例如:com.guoxiaoxing.CustomView,那麼這裏就有個.了,可以利用這一點判定是內置View 還是自定義View,Google的工程師很機智的。😎
關於view標籤
<view
class="RelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
在使用時,相當於所有控件標籤的父類一樣,可以設置class屬性,這個屬性會決定view這個節點會是什麼控件。
關於BlinkLayout
這個也是個冷門的控件,本質上是一個FrameLayout,被它包裹的控件會像電腦版的QQ小企鵝那樣一直閃爍。
<blink
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這個控件會一直閃爍"/>
</blink>
關於onCreateView()與createView()
這兩個方法在本質上都是一樣的,只是onCreateView()會給內置的View前面加一個前綴,例如:android.widget,方便開發者在寫內置View的時候,不用謝全路徑名。 前面我們也提到了LayoutInflater是一個抽象類,我們實際使用的PhoneLayoutInflater,這個類的實現很簡單,它重寫了LayoutInflater的onCreatView()方法,該 方法就是做了一個給內置View加前綴的事情。
public class PhoneLayoutInflater extends LayoutInflater {
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app."
};
@Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
//循環遍歷三種前綴,嘗試創建View
for (String prefix : sClassPrefixList) {
try {
View view = createView(name, prefix, attrs);
if (view != null) {
return view;
}
} catch (ClassNotFoundException e) {
// In this case we want to let the base class take a crack
// at it.
}
}
return super.onCreateView(name, attrs);
}
public LayoutInflater cloneInContext(Context newContext) {
return new PhoneLayoutInflater(this, newContext);
}
}
這樣一來,真正的View構建還是在createView()方法裏完成的,createView()主要根據完整的類的路徑名利用反射機制構建View對象,我們具體來 看看createView()方法的實現。
public abstract class LayoutInflater {
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
//1. 從緩存中讀取構造函數。
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
//2. 沒有在緩存中查找到構造函數,則構造完整的路徑名,並加裝該類。
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);
}
}
//3. 從Class對象中獲取構造函數,並在sConstructorMap做下緩存,方便下次使用。
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else {
//4. 如果sConstructorMap中有當前View構造函數的緩存,則直接使用。
if (mFilter != null) {
// Have we seen this name before?
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// New class -- remember whether it is allowed
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;
//5. 利用構造函數,構建View對象。
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
} catch (NoSuchMethodException e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + (prefix != null ? (prefix + name) : name), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (ClassCastException e) {
// If loaded class is not a View subclass
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Class is not a View " + (prefix != null ? (prefix + name) : name), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (ClassNotFoundException e) {
// If loadClass fails, we should propagate the exception.
throw e;
} catch (Exception e) {
final InflateException ie = new InflateException(
attrs.getPositionDescription() + ": Error inflating class "
+ (clazz == null ? "<unknown>" : clazz.getName()), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
}
好了,講到這裏一個佈局xml資源文件的查找和解析流程就分析完了。