【问题标题】:How to set ImageButton's foreground image to nothing如何将 ImageButton 的前景图像设置为空
【发布时间】:2013-01-03 22:27:59
【问题描述】:

我有一些 ImageButtons 被用作分段控件,每个都有一个背景集,前景图像将是一个复选标记,显示当前选择了 3 个中的哪一个。其他 2 个按钮应该没有前景图像。图像在 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);

如何清除图像,或者只隐藏前景图像而保留显示背景图像?

【问题讨论】:

  • 只需设置imgButton.setImageResource(0);
  • 好的,试过了,但仍然出现空指针崩溃,所以我想我的问题是按钮由于某种原因为空。谢谢。
  • @jamone - 可能。 setImageDrawable(null);应该与 setImageResource(0); 一起正常工作

标签: android android-layout


【解决方案1】:

来自android documentation

 public void setBackgroundResource (int resid)

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

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

sepiaModeButton.setImageResource(0);

而不是

sepiaModeButton.setImageDrawable(null);

【讨论】:

  • 虽然sepidModeButton.setImageResource(0) 确实有效,但它的工作方式无法预测。有时在它被称为复选标记后仍然显示,有时它会消失。我最终创建了一个透明的可绘制对象。
  • 我想是因为你也应该删除背景吗?
【解决方案2】:

您可以创建一个 Transclude drawable 例如,在您的 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

【讨论】:

  • 谢谢,这将对应用程序的其他部分有所帮助。
猜你喜欢
  • 1970-01-01
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-06-23
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
相关资源
最近更新 更多