如何将ImageButton的前景图像设置为空

时间:2013-01-03 14:07:13

标签: android android-layout

我有一些ImageButtons被用作分段控件,每个都有一个背景设置,而forground图像将是一个复选标记,显示当前选择了哪一个。其他2个按钮应该没有forground图像。图像以XML格式定义(见下文)。

            <ImageButton
                android:id="@+id/style_light_button"
                android:layout_width="@dimen/style_color_segment_width"
                android:layout_height="@dimen/style_button_segment_height"
                android:background="@drawable/button_segmented_light"
                android:src="@drawable/icons_checkmark_dark" />

            <ImageButton
                android:id="@+id/style_sepia_button"
                android:layout_width="@dimen/style_color_segment_width"
                android:layout_height="@dimen/style_button_segment_height"
                android:background="@drawable/button_segmented_sepia"
                android:src="@drawable/icons_checkmark_dark" />

            <ImageButton
                android:id="@+id/style_dark_button"
                android:layout_width="@dimen/style_color_segment_width"
                android:layout_height="@dimen/style_button_segment_height"
                android:background="@drawable/button_segmented_dark"
                android:src="@drawable/icons_checkmark_light" />

在单击一个代码的代码中,我将清除2中未单击的复选标记,并确保将其添加到单击的那个。

ImageButton lightModeButton = (ImageButton)findViewById(R.id.style_light_button);
ImageButton sepiaModeButton = (ImageButton)findViewById(R.id.style_sepia_button);
ImageButton darkModeButton = (ImageButton)findViewById(R.id.style_dark_button);

我已经尝试了setImageBitmap(null)setImageDrawable(null),但它们都崩溃了。

lightModeButton.setImageBitmap(null);
sepiaModeButton.setImageDrawable(null);
darkModeButton.setImageResource(R.drawable.icons_checkmark_light);

如何清除图像,或者只是隐藏前景图像,同时保留背景图像?

2 个答案:

答案 0 :(得分:2)

来自android documentation

 public void setBackgroundResource (int resid)

将背景设置为给定资源。资源应引用Drawable对象或0以删除背景。

我不知道它是否适用于setImageResource(int resId)所以请试一试:

sepiaModeButton.setImageResource(0);

而不是

sepiaModeButton.setImageDrawable(null);

答案 1 :(得分:1)

您可以在Drawable目录创建文件上创建Transclude drawable transclude_drawable.xml像这样:

<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@android:color/transparent" />
</selector>

之后只需设置ImageButton.setImageResource(R.drawable.transclude_drawable); 不要忘记更改ImageButton与您的引用,例如lightModeButton