在自定义控件属性的时候,在代码中利用了obtainStyledAttributes的方法获取TypedArray,但是TyptedArray一直是空的,在提供的attrs中我可以查到attributeName和attributeNameResource,但是确得不到正确的值,这个问题困惑了两天。场景如下:
attrs.xml中的定义:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TriangleLoadingViewAttr">
<attr name="test" format="integer" />
<attr name="state">
<flag name="normal" value="1" />
<flag name="dynamic" value="2" />
</attr>
</declare-styleable>
</resources>
layout.XML中的定义:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:triangle="http://schemas.android.com/apk/com.yxp.triangleloadingview"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.yxp.triangleloadingview.TriangleLoadingView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
triangle:state="normal"
triangle:test="22"/>
</RelativeLayout>
代码中的定义:
if (attrs != null) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TriangleLoadingViewAttr, 0, 0);
String str = typedArray.getString(R.styleable.TriangleLoadingViewAttr_state);
int test = typedArray.getInt(R.styleable.TriangleLoadingViewAttr_test, -1);
status = typedArray.getInt(R.styleable.TriangleLoadingViewAttr_state, STATUS_DYNAMIC);
typedArray.recycle();
}
这就是错误的场景,实在没有发现任何的问题。。。
后来在stackoverflow的查找下,才发现,在SDK 17之后,自定义属性的引入的语句,不应该加包名,而是res-auto
xmlns:triangle="http://schemas.android.com/apk/com.yxp.triangleloadingview"
改为
xmlns:triangle="http://schemas.android.com/apk/res-auto"
虽然最后结局是好的,但过程很痛苦。