android.content.res.Resources $ NotFoundException以编程方式设置android.R.attr.listChoiceIndicatorMultiple

dbm*_*dbm 12 android listviewitem checkedtextview

我正在尝试以编程方式在ListView中的CheckedTextView项目上设置"android:checkMark"属性.运行我的应用程序时,我得到以下异常:

android.content.res.Resources$NotFoundException: Resource ID #0x101021a
Run Code Online (Sandbox Code Playgroud)

ID#0x101021a的资源对应于android.R.attr.listChoiceIndicatorMultiple,这正是我传递给CheckedTextView的值:

mCheckedTextView.setCheckMarkDrawable(android.R.attr.listChoiceIndicatorMultiple)
Run Code Online (Sandbox Code Playgroud)

这不是用Java做的吗?我尝试(并成功)从XML布局触发所需的行为:

<CheckedTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:id="@android:id/text1" />
Run Code Online (Sandbox Code Playgroud)

问题是我在编译时不知道它应该是什么

android:checkMark="?android:attr/listChoiceIndicatorMultiple"
Run Code Online (Sandbox Code Playgroud)

要么

android:checkMark="?android:attr/listChoiceIndicatorSingle"
Run Code Online (Sandbox Code Playgroud)

因此,我需要在运行时设置这些值.

Chr*_*Orr 26

我猜想以编程方式设置属性引用而不是Drawable引用是问题所在.

在这种情况下,android.R.attr.listChoiceIndicatorMultiple 对应于 android.R.drawable.btn_check,所以你可以尝试设置它.


或者,如果你能获得的属性,你可以调用getDrawable()TypedArray动态获取Drawable值.

编辑:
由于值listChoiceIndicatorMultiple取决于当前主题,您需要询问当前主题以解析引用:

int[] attrs = { android.R.attr.listChoiceIndicatorMultiple };
TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs);
Drawable indicator = ta.getDrawable(0);
view.setCheckMarkDrawable(indicator);
ta.recycle();
Run Code Online (Sandbox Code Playgroud)

一定要缓存drawables,而不是为你的每个项目执行此操作ListView.

这只是一个非常基本的例子,但它适用于默认主题.attrs如果您有自定义主题,我不确定要完全解决需要做什么.