【问题标题】:Declared XML styleable cannot be found from code无法从代码中找到声明的 XML 样式
【发布时间】:2014-06-25 13:22:57
【问题描述】:

我正在尝试将自定义属性 (@drawable) 添加到我的自定义视图中,并且我想将其作为 resourceId 进行检索。如果我想通过代码访问它,我的视图以某种方式找不到它:

TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TouchImageView, defStyle, 0);
int base = a.getResourceId(R.styleable.imageDrawable, R.drawable.kaart);

我得到的错误是: 无法解析或不是字段

我的 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"/>

【问题讨论】:

  • 你需要在你的TouchImageView classimport yourPKG.R;
  • 是的,我这样做了。它确实识别 R 但不识别 R.styleable.imageDrawable

标签: android xml android-custom-view declare-styleable


【解决方案1】:

啊,这很容易。显然 styleable 必须用作属性的前缀,如下所示:TouchImageView_imageDrawable。所以新的代码是:

int base = a.getResourceId(R.styleable.TouchImageView_imageDrawable, R.drawable.kaart);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多