如何在Android中设置视图的不透明度(Alpha)

245

我有一个按钮,如下所示:

<Button 
     android:text="Submit" 
     android:id="@+id/Button01" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content">
</Button>

在我的onCreate()事件中,我这样调用Button01:

setContentView(R.layout.main);

View Button01 = this.findViewById(R.id.Button01);
Button01.setOnClickListener(this);

应用程序中有一个背景,我想将这个提交按钮设置为一个不透明度。我该如何在这个视图上设置一个不透明度?我可以在Java端设置,还是可以在main.xml文件中设置?

在Java端,我尝试使用 Button01.mutate().SetAlpha(100),但是出现了错误。

13个回答

6

对于API < 11的textView颜色,我采取了以下措施:

int textViewColor = textView.getTextColors().getDefaultColor(); 
textView.setTextColor(Color.argb(128, Color.red(textViewColor), Color.green(textViewColor), Color.blue(textViewColor))); //50% transparent

有点繁琐,但是它行得通 :-)


6

如果你使用 Kotlin ,设置 alpha 值非常容易,只需这样做:

imageView.alpha= 0.5F

该值必须是一个浮点数


1

我知道这个问题已经有很多答案了,但是对于按钮来说,最简单的方法就是创建自己的 .xml 选择器,并将其设置为按钮的背景。这样,您还可以在按下或启用时更改它的状态等。这是我使用的一个快速片段示例。如果您想向任何颜色添加透明度,请添加前导十六进制值(#XXcccccc)。 (XX ==“颜色的alpha值”)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#70c656" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#70c656"
                android:endColor="#53933f"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接