将 Android CheckBox 设置为不同的图像...然后返回原始图像

Car*_*rol 2 checkbox sdk android imageview

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

    mCheck = (CheckBox) findViewById(R.id.chkMine);
    mCheck.setButtonDrawable(R.drawable.my_image);
Run Code Online (Sandbox Code Playgroud)

我看到很多人要求这样做。但我从来没有看到第二部分:

How do I put BACK the original checkbox imagery, later in my code?
Run Code Online (Sandbox Code Playgroud)

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

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

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

谢谢。

MH.*_*MH. 5

正如您已经正确提到自己的那样,不幸的是getButtonDrawable(),在替换之前无法获得对所使用的可绘制对象的引用。显然,您可以将 Android 的资源复制到您的本地项目并使用它们来重置CheckBox's 按钮,但这意味着您必须考虑主题的所有不同样式,更不用说设备制造商可能对这些资源进行的任何更改. 沿着这条路走并不是不可能的,但你会发现对于听起来很简单的事情来说会很麻烦。

您可能需要考虑执行以下操作:查询资源以获取您需要的可绘制对象的资源 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;
}
Run Code Online (Sandbox Code Playgroud)

下面是将按钮可绘制设置为某些自定义图像的快速示例,然后将其重置。每当检查状态发生变化时,我只是在应用程序图标和可绘制的原始按钮之间切换。

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));
    }
});
Run Code Online (Sandbox Code Playgroud)