2

我正在使用以下(非常常见的)代码来更改我的 Android 应用程序中的复选框图像。

    mCheck = (CheckBox) findViewById(R.id.chkMine);
    mCheck.setButtonDrawable(R.drawable.my_image);

我看到很多人都在问这个。但我从来没有看到第二部分:

How do I put BACK the original checkbox imagery, later in my code?

我犹豫是否尝试设计我自己的所有图像(选中、未选中、重影检查、重影未选中等),因为我需要通常出现在许多不同版本的 Android 上的原始图像。

也许,最初使用(不存在?) getButtonDrawable() 调用保存默认图像,然后再使用它?

我认为这就像第二次调用 setButtonDrawable() 来“撤消”我的更改一样简单。或者是吗?

谢谢。

4

2 回答 2

5

正如您已经正确提到自己的那样,不幸的是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));
    }
});
于 2012-04-20T21:16:37.747 回答
0

我认为检索原始图像的调用setButtonDrawable()应该再次起作用。
但是,您将引用android 的原始资源,而不是您的资源

mCheck = (CheckBox) findViewById(R.id.chkMine);
mCheck.setButtonDrawable(android.R.drawable.*);

可能您必须自己查找文件名:

platforms > android-* > data > res > drawable-*
(source: accepted answer)

编辑
哈!我知道我以前看过那个网站:Android R Drawables ^^v
感谢 Mef

于 2012-04-19T19:33:42.807 回答