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

以编程方式设置android.R.attr.listChoiceIndicatorMultiple时,android.content.res.Resources$NotFoundException,android,listviewitem,checkedtextview,Android,Listviewitem,Checkedtextview,我正试图以编程方式在ListView中的CheckedTextView项上设置“android:checkMark”属性。运行我的应用程序时,出现以下异常: android.content.res.Resources$NotFoundException: Resource ID #0x101021a ID为0x101021a的资源对应于android.R.attr.ListChoiceIndicator Multiple,这正是我传递给CheckedTextView的值: mCheckedTe

我正试图以编程方式在ListView中的CheckedTextView项上设置“android:checkMark”属性。运行我的应用程序时,出现以下异常:

android.content.res.Resources$NotFoundException: Resource ID #0x101021a
ID为0x101021a的资源对应于android.R.attr.ListChoiceIndicator Multiple,这正是我传递给CheckedTextView的值:

mCheckedTextView.setCheckMarkDrawable(android.R.attr.listChoiceIndicatorMultiple)
这不是从Java实现的方法吗?我尝试(并成功)从XML布局触发所需的行为:

<CheckedTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:id="@android:id/text1" />


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

我想问题在于通过编程方式设置属性引用,而不是
可绘制的
引用

在本例中,
android.R.attr.ListChoiceIndicator多个
android.R.drawable.btn\u检查
,因此您可以尝试设置它


或者,如果可以获取属性,可以调用
TypedArray
动态获取
Drawable

编辑:
由于
listcooiceindicator multiple的值取决于当前主题,因此需要请求当前主题解析引用:

int[] attrs = { android.R.attr.listChoiceIndicatorMultiple };
TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs);
Drawable indicator = ta.getDrawable(0);
view.setCheckMarkDrawable(indicator);
ta.recycle();
请确保缓存可绘图项,而不是对
列表视图中的每个项目执行此操作


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

如果使用appcompat库,简单的替代方案是:

setCheckMarkDrawable(android.support.v7.appcompat.R.drawable.abc_btn_check_material);
或:


这是一个非常好的答案(因为我已经走过了这条路:-),但是,似乎没有“android.R.drawable.btn_check”drawable。如果我浏览文件系统,我确实找到了它(它在“[path_to_android_SDK]/platforms/android-9/data/res/drawable”文件夹中,它是一个XML文件),但在编写相应的代码时,我会收到编译错误,抱怨“btn_检查无法解决或不是有效字段”。然而,另一个建议(关于“getDrawable()”的建议)是,对我来说是新的。不过,我得做一些“家庭作业”,因为我以前从未做过这样的操作:-)啊,是的,你说得对。我添加了一个非常基本的代码示例,非常适合我。谢谢!你的代码工作起来很有魅力!对于设备上有自定义主题且无法从主题中获取“…多个”各自“…单个”指标的情况,我很可能会实施一个回退解决方案。再次感谢您提供的高质量帮助(如果可以的话,我会一遍又一遍地投票支持这个答案:-)对@Christopher的缓存建议的快速评论:我还没有找到一种安全的方法来缓存建议的可拖动设备。如果我进行缓存,似乎我的所有列表项都将获得与我单击的项相同的状态。是的,我调用了“indicator.mutate()”。目前我依赖于我的适配器,它成功地在创建/重用列表项时正确重用了“convertView”,以减少不必要的可绘制数据。谢谢!这对我今天遇到的问题帮助很大。
int[] attrs = { android.R.attr.listChoiceIndicatorMultiple };
TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs);
Drawable indicator = ta.getDrawable(0);
view.setCheckMarkDrawable(indicator);
ta.recycle();
setCheckMarkDrawable(android.support.v7.appcompat.R.drawable.abc_btn_check_material);
setCheckMarkDrawable(android.support.v7.appcompat.R.drawable.abc_btn_radio_material);