Android 从代码中找不到声明的XML可样式化
我正在尝试将自定义属性(@drawable)添加到自定义视图中,并希望将其作为resourceId检索。如果我想通过代码访问它,我的视图无法找到它:Android 从代码中找不到声明的XML可样式化,android,xml,android-custom-view,declare-styleable,Android,Xml,Android Custom View,Declare Styleable,我正在尝试将自定义属性(@drawable)添加到自定义视图中,并希望将其作为resourceId检索。如果我想通过代码访问它,我的视图无法找到它: TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TouchImageView, defStyle, 0); int base = a.getResourceId(R.styleable.imageDrawable, R.drawable.kaar
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TouchImageView, defStyle, 0);
int base = a.getResourceId(R.styleable.imageDrawable, R.drawable.kaart);
我得到的错误是:
无法解析或不是字段
My attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TouchImageView">
<attr name="imageDrawable" format="string"/>
</declare-styleable>
</resources>
布局中的xml将是:
<nl.raakict.android.util.TouchImageView
android:id="@+id/plattegrond"
android:layout_width="match_parent"
android:layout_height="match_parent"
imageDrawable="@drawable/kaart"/>
int base = a.getResourceId(R.styleable.TouchImageView_imageDrawable, R.drawable.kaart);
啊,这很容易。显然,styleable必须用作属性的前缀,如:TouchImageView\u imageDrawable。因此,新的准则是:
<nl.raakict.android.util.TouchImageView
android:id="@+id/plattegrond"
android:layout_width="match_parent"
android:layout_height="match_parent"
imageDrawable="@drawable/kaart"/>
int base = a.getResourceId(R.styleable.TouchImageView_imageDrawable, R.drawable.kaart);
您需要
导入您的pkg.R
在您的TouchImageView类中
是的,我这样做了。它可以识别R,但不能识别R.styleable.imageDrawable