TypedArray流程分析

obtainStyledAttributes_flow.png

Context#obtainStyledAttributes

// 调用Resources.Theme的obtainStyledAttributes方法
return getTheme().obtainStyledAttributes(attrs);

在Context中的getTheme方法是抽象方法,那我们得看他的子类的具体实现,我们一般会在自定义View的时候调用此方法,而自定义View中的Context是传进来的,一般指的是它显示的Activity,我们在Activity中搜索getTheme方法,会搜索到它的父类ContextThemeWrapper中,那我们来看看ContextThemeWrapper中getTheme怎么实现的:

ContextThemeWrapper#getTheme

  1. 根据版本选择默认主题并保存在mThemeResource中
mThemeResource = Resources.selectDefaultTheme(mThemeResource,
        getApplicationInfo().targetSdkVersion);
  1. 初始化主题
initializeTheme();

在initializeTheme方法内部的实现原理:最终调用了AssetManager的native方法applyThemeStyle

Context#obtainStyledAttributes

Context类中有4个obtainStyledAttributes, 最终调用的都是4个参数的obtainStyledAttributes方法,而最终调用的是ResourcesImpl.ThemeImpl的obtainStyledAttributes方法。让我们看看Context的obtainStyledAttributes方法的4个参数分别代表着什么:

  • AttributeSet set :AttributeSet是在布局中定义的一系列属性的集合,包括系统定义的属性。在下列例子中,如layout_width,还有自定义的属性,如MyProgress
  • @StyleableRes int[] attrs :自定义属性集合,在下列例子中,如R.styleable.MyView
  • @AttrRes int defStyleAttr :在当前主题中有一個引用指向样式文件,這個样式文件将 TypedArray 设置默认值。如果此参数为0即表示不进行默认值设置。在下列例子中,如R.attr.DefaultViewStyleAttr
  • @StyleRes int defStyleRes :默认的样式资源文件,只有当 defStyleAttr 为 0 或者无法在对应的主题下找到资源文件时才起作用。如果此参数为0即表示不进行默认值设置。在下列例子中,如R.style.DefaultViewStyleRes

以自定义View为例,现在创建一个MyView:

public MyView(Context context, @Nullable AttributeSet attrs) {
    Logger logger = Logger.getLogger("MyView");
    for (int i = 0; i < attrs.getAttributeCount(); i++) {
        logger.info(attrs.getAttributeName(i) + " : " + attrs.getAttributeValue(i));
    }
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView, R.attr.DefaultViewStyleAttr, R.style.DefaultViewStyleRes);
    logger.info("-----------------------------------------");
    logger.info("MyText1的最终值" + " : " + a.getString(R.styleable.MyView_MyText1));
    logger.info("MyText2的最终值" + " : " + a.getString(R.styleable.MyView_MyText2));
    logger.info("MyText3的最终值" + " : " + a.getString(R.styleable.MyView_MyText3));
    logger.info("MyText4的最终值" + " : " + a.getString(R.styleable.MyView_MyText4));
    logger.info("MyText5的最终值" + " : " + a.getString(R.styleable.MyView_MyText5));
}

在attr.xml中自定义属性:

<declare-styleable name="MyView">
    <attr name="MyText1" format="string" />
    <attr name="MyText2" format="string" />
    <attr name="MyText3" format="string" />
    <attr name="MyText4" format="string" />
    <attr name="MyText5" format="string" />
</declare-styleable>

在styles.xml中自定义style

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="DefaultViewStyleAttr">@style/MyViewStyleAttr</item>
    <item name="MyText1">"defStyleAttr中提供的默认的属性值,在主题中直接定义"</item>
    <item name="MyText2">"defStyleAttr中提供的默认的属性值,在主题中直接定义"</item>
    <item name="MyText3">"defStyleAttr中提供的默认的属性值,在主题中直接定义"</item>
    <item name="MyText4">"defStyleAttr中提供的默认的属性值,在主题中直接定义"</item>
</style>

<style name="MyViewStyle">
    <item name="MyText1">"XML中在style里定义的属性值"</item>
    <item name="MyText2">"XML中在style里定义的属性值"</item>
</style>

<style name="DefaultViewStyleRes">
    <item name="MyText1">"defStyleRes中提供的默认的属性值"</item>
    <item name="MyText2">"defStyleRes中提供的默认的属性值"</item>
    <item name="MyText3">"defStyleRes中提供的默认的属性值"</item>
    <item name="MyText4">"defStyleRes中提供的默认的属性值"</item>
    <item name="MyText5">"defStyleRes中提供的默认的属性值"</item>
</style>

<attr name="DefaultViewStyleAttr" format="reference" />

<style name="MyViewStyleAttr">
    <item name="MyText1">"defStyleAttr中提供的默认的属性值,在主题中的style里定义"</item>
    <item name="MyText2">"defStyleAttr中提供的默认的属性值,在主题中的style里定义"</item>
    <item name="MyText3">"defStyleAttr中提供的默认的属性值,在主题中的style里定义"</item>
</style>

在布局文件中引用这个MyView:

<com.cn.zero.gesture.MyView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/MyViewStyle"
    app:MyText1="XML中直接定义的属性值" />

运行之后输出的结果是:

I/MyView: layout_width : -1
I/MyView: layout_height : -2
I/MyView: MyText1 : XML中直接定义的属性值
I/MyView: style : @style/MyViewStyle
I/MyView: -----------------------------------------
I/MyView: MyText1的最终值 : XML中直接定义的属性值
I/MyView: MyText2的最终值 : XML中在style里定义的属性值
I/MyView: MyText3的最终值 : defStyleAttr中提供的默认的属性值,在主题中的style里定义
I/MyView: MyText4的最终值 : defStyleAttr中提供的默认的属性值,在主题中直接定义
I/MyView: MyText5的最终值 : null

从上面的结果来看,xml attributes > xml style > theme style defStyleAttr > theme defStyleAttr > defStyleRes

**上面例子的代码不变,我们将defStyleAttr设为0,如: **

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView, 0, R.style.DefaultViewStyleRes);

运行之后输出的结果是:

I/MyView: layout_width : -1
I/MyView: layout_height : -2
I/MyView: MyText1 : XML中直接定义的属性值
I/MyView: style : @style/MyViewStyle
I/MyView: -----------------------------------------
I/MyView: MyText1的最终值 : XML中直接定义的属性值
I/MyView: MyText2的最终值 : XML中在style里定义的属性值
I/MyView: MyText3的最终值 : defStyleRes中提供的默认的属性值
I/MyView: MyText4的最终值 : defStyleRes中提供的默认的属性值
I/MyView: MyText5的最终值 : defStyleRes中提供的默认的属性值

此时,MyText3、MyText4、MyText5的最终值都变成了在DefaultViewStyleRes中定义的属性的值了。可以得知在defStyleAttr中检索不到值,才会去取defStyleRes中设置的值。

一般设置属性的默认值,都会使用defStyleRes来设置。

Context#obtainStyledAttributes

return getTheme().obtainStyledAttributes(
    set, attrs, defStyleAttr, defStyleRes);

ResourcesImpl.ThemeImpl#obtainStyledAttributes

  1. 调用TypedArray的obtain方法
final TypedArray array = TypedArray.obtain(Resources.this, len);
  1. 调用本地方法给array(TypedArray)的mData、mIndices赋值
AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, array.mData, array.mIndices);

查看本地方法applyStyle的具体实现,是在mData数组中存储了六种类型的数据,分别为:

  • STYLE_TYPE
  • STYLE_DATA
  • STYLE_ASSET_COOKIE
  • STYLE_RESOURCE_ID
  • STYLE_CHANGING_CONFIGURATIONS
  • STYLE_DENSITY
  • STYLE_NUM_ENTRIES
    base/core/jni/android_util_AssetManager.cpp查看android_content_AssetManager_applyStyle
// Write the final value back to Java.
dest[STYLE_TYPE] = value.dataType;
dest[STYLE_DATA] = value.data;
dest[STYLE_ASSET_COOKIE] = block != kXmlBlock ?
     static_cast<jint>(res.getTableCookie(block)) : -1;
dest[STYLE_RESOURCE_ID] = resid;
dest[STYLE_CHANGING_CONFIGURATIONS] = typeSetFlags;
dest[STYLE_DENSITY] = config.density;

TypedArray#obtain

  1. 从Resource.mTypedArrayPool(SynchronizedPool<TypedArray>)池中取TypedArray对象
final TypedArray attrs = res.mTypedArrayPool.acquire();
...
  1. 没取到,则调用TypedArray的构造方法
return new TypedArray(res,
                new int[len*AssetManager.STYLE_NUM_ENTRIES],
                new int[1+len], len);

在TypedArray中我们会看到很多getxxx()方法,我们点进去看会发现基本上都会有这么一行代码:

if (mRecycled) {
    throw new RuntimeException("Cannot make calls to a recycled instance!");
}

猜测:这段代码会不会和每次在自定义View中取完自定义属性之后调用的typedArray.recycle();有关?

if (mRecycled) {
    throw new RuntimeException(toString() + " recycled twice!");
}
mRecycled = true;
// These may have been set by the client.
...
mResources.mTypedArrayPool.release(this);

查看recycle()方法,可以知道Android要求我们在每次不再使用TypedArray时,必须手动调用该方法以复用TypedArray
注意:

  1. 不能重复调用该方法,否则会抛出以下异常:
Caused by: java.lang.RuntimeException: [0, 0, 1, 0, ...] recycled twice!
  1. 不能在调用该方法后,还调用getxxx等TypedArray的方法,否则回抛出以下异常:
Caused by: java.lang.RuntimeException: Cannot make calls to a recycled instance!

TypedArray#getInt

  1. 根据下标index获取mData数组存储的Type类型的值,判断Type是否为TypedValue.TYPE_NULL,true则,返回默认值defValue
...
final int type = data[index+AssetManager.STYLE_TYPE];
if (type == TypedValue.TYPE_NULL) {
            return defValue;
        } 
  1. 根据下标index获取data、assetCookie、resourceId、changingConfigurations、density等类型的值,并存储在TypedValue中
getValueAt(index, v)
  1. 通过XmlUtils.convertValueToInt方法将诸如"-12,0xa1,014,#fff"这类字符串转化为真正的数值
return XmlUtils.convertValueToInt(v.coerceToString(), defValue);

TypedArray$getValueAt

将mData数组数组中的数据存储在TypedValue中:

...
outValue.type = type;
outValue.data = data[index+AssetManager.STYLE_DATA];
outValue.assetCookie = data[index+AssetManager.STYLE_ASSET_COOKIE];
outValue.resourceId = data[index+AssetManager.STYLE_RESOURCE_ID];
outValue.changingConfigurations = data[index+AssetManager.STYLE_CHANGING_CONFIGURATIONS];
outValue.density = data[index+AssetManager.STYLE_DENSITY];
outValue.string = (type == TypedValue.TYPE_STRING) ? loadStringValueAt(index) : null;

XmlUtils$convertValueToInt

  1. 转换负数
if ('-' == nm.charAt(0)) {
    sign = -1;
    index++;
}
  1. 转换十六进制和八进制
if ('0' == nm.charAt(index)) {
    //  Quick check for a zero by itself
    if (index == (len - 1))
        return 0;
    char    c = nm.charAt(index + 1);
    if ('x' == c || 'X' == c) {
        index += 2;
        base = 16;
    } else {
        index++;
        base = 8;
    }
}
  1. 转换颜色数值
else if ('#' == nm.charAt(index))
{
    index++;
    base = 16;
}
  1. 将String转换成数值
Integer.parseInt(nm.substring(index), base) * sign;

总结

  1. TypedArray是用来检索项目中各种资源的
  2. 只有当 defStyleAttr 为 0 或者无法在对应的主题下找到资源文件时才起作用,defStyleRes中定义的默认样式才起作用
  3. TypedArray检索完资源,必须调用recycle方法来循环使用

参考:
A deep dive into Android View constructors
http://blog.csdn.net/luoshengyang/article/details/8738877

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,444评论 4 365
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,867评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,157评论 0 248
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,312评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,673评论 3 289
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,802评论 1 223
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,010评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,743评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,470评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,696评论 2 250
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,187评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,538评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,188评论 3 240
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,127评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,902评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,889评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,741评论 2 274

推荐阅读更多精彩内容