正如您已经正确提到自己的那样,不幸的是getButtonDrawable()
,在替换它之前没有对所使用的可绘制对象的引用。显然,您可以将 Android 的资源复制到本地项目并使用这些资源来重置CheckBox
' 按钮,但这意味着您必须考虑主题的所有不同样式,更不用说设备制造商可能对这些资源进行的任何更改. 走这条路并非不可能,但你会发现对于听起来很简单的事情会很麻烦。
您可能要考虑执行以下操作:在资源中查询您需要的可绘制对象的资源 ID。这样您就不必明确地处理不同的主题,因为查找会这样做。您只需几行即可轻松将此功能放入专用方法中。例子:
private static int getDefaultCheckBoxButtonDrawableResourceId(Context context) {
// pre-Honeycomb has a different way of setting the CheckBox button drawable
if (Build.VERSION.SDK_INT <= 10) return Resources.getSystem().getIdentifier("btn_check", "drawable", "android");
// starting with Honeycomb, retrieve the theme-based indicator as CheckBox button drawable
TypedValue value = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.listChoiceIndicatorMultiple, value, true);
return value.resourceId;
}
下面是一个将可绘制按钮设置为一些自定义图像的快速示例,然后将其重置。每当检查状态发生变化时,我只是在应用程序图标和可绘制的原始按钮之间切换。
CheckBox mCheckBox = (CheckBox) findViewById(R.id.checkbox);
mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override public void onCheckedChanged(CompoundButton button, boolean isChecked) {
button.setButtonDrawable(isChecked ? R.drawable.icon : getDefaultCheckBoxButtonDrawableResourceId(StackOverflowActivity.this));
}
});