大家都知道android 里面引用资源,我们用R.drawable.xx就可以引用到我们想要的资源,其实我们都不知道,在这简单的,有系统的努力在支持着。其实大家可以想到我们想要获取一个drawable图片资源的时候也可以这样:Resource res=getResource();
res.getDrawable(R.drawble.icon);
下面我们来学习一下Resource类。继续上面所说的,查找资源我们想看一下getDrawable的函数原型
public Drawable getDrawable(int id) throws NotFoundException {
synchronized (mTmpValue) {
TypedValue value = mTmpValue;
getValue(id, value, true);
return loadDrawable(value, id);
}
}
就是通过一个资源的id返回一个drawable。我们继续向下看。
Drawable.ConstantState cs = sPreloadedDrawables.get(key);
if (cs != null) {
dr = cs.newDrawable(this);
} else {
if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT &&
value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
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 (DEBUG_LOAD) Log.v(TAG, "Loading drawable for cookie "
+ value.assetCookie + ": " + file);
if (file.endsWith(".xml")) {
try {
XmlResourceParser rp = loadXmlResourceParser(
file, id, value.assetCookie, "drawable");
dr = Drawable.createFromXml(this, rp);
rp.close();
} catch (Exception e) {
NotFoundException rnf = new NotFoundException(
"File " + file + " from drawable resource ID #0x"
+ Integer.toHexString(id));
rnf.initCause(e);
throw rnf;
}
} else {
try {
InputStream is = mAssets.openNonAsset(
value.assetCookie, file, AssetManager.ACCESS_STREAMING);
// System.out.println("Opened file " + file + ": " + is);
dr = Drawable.createFromResourceStream(this, value, is,
file, null);
is.close();
// System.out.println("Created stream: " + dr);
} catch (Exception e) {
NotFoundException rnf = new NotFoundException(
"File " + file + " from drawable resource ID #0x"
+ Integer.toHexString(id));
rnf.initCause(e);
throw rnf;
}
}
}
}
这里会去查找value的值,最终通过AssetManager读取我们安装文件里面的文件。
到这里大家都应该明白了吧!在我们最简单的引用背后,系统是如何帮我们查找资源的,其实还是通过流的形式,大家可能会问那这么R.drawable.xx有什么关系,其实到Drawable还有一个转换的过程,大家自己去查找看吧。
下一次讲解关于横竖屏切换实现原理,也是与Resource类有关的。