如何在 Android 中以编程方式仅显示/隐藏 ImageView 的背景?

问题描述 投票:0回答:0

我有一个

ImageView
,它的 alpha 在 XML 中设置为 0。 XML 看起来像这样:

<LinearLayout

            android:layout_width="match_parent"
            android:layout_height="<height>"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/<id>"
                android:layout_width="<width>"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:alpha="0"
                android:background="#ff00ff"
                android:clickable="true"
                android:focusable="true"
                app:srcCompat="@drawable/<drawable>" />

            <ImageView
                android:id="@+id/<id>"
                android:layout_width="<width>"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:alpha="0"
                android:background="#0000ff"
                android:clickable="true"
                android:focusable="true"
                app:srcCompat="@drawable/<drawable>" />

</LinearLayout>

我试着搜索如何做到这一点,但大多数问题都是关于如何隐藏背景或整个

ImageView
,而不仅仅是背景。此外,
alpha
必须设置为
"0"
。有没有办法只隐藏图像,以便只有背景(纯色)可见?只需要显示两个
ImageView
的背景颜色,所以容器(
LinearLayout
)的
background
不能用于两者(背景颜色不同)。

将图像的来源更改为与背景颜色相同的纯色图像会起作用,但我需要以编程方式更改此颜色,因此效率可能很低。我还尝试了

ImageView.
-
setAlpha(float)
setImageAlpha(int)
setImageResource(int)
(到
0
)和
setImageDrawable(Drawable)
(再次显示图像,背景[颜色])的不同组合,但他们产生奇怪的结果。使用
setImageResource(0)
(带 alpha
1f
)隐藏图像,仅显示纯色背景,但我无法再次显示图像。有什么我不知道的简单方法吗?

我需要以编程方式执行此操作,因此 Java android Linearlayout set two colors 中的方法不起作用。以编程方式执行此操作的最佳方法是什么?

java android android-imageview alpha android-background
© www.soinside.com 2019 - 2024. All rights reserved.