我有一个按钮如下:

<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),但它给了我一个错误。


当前回答

我惊讶于其他人更复杂的答案。

XML

你可以非常简单地在你的xml中按钮(或任何其他视图)的颜色定义中定义alpha:

android:color="#66FF0000"    // Partially transparent red

在上面的例子中,颜色是部分透明的红色。

当定义视图的颜色时,格式可以是#RRGGBB或#AARRGGBB,其中AA是十六进制alpha值。FF是完全不透明的00是完全透明的。

动态

如果您需要动态更改代码中的不透明度,请使用

myButton.getBackground().setAlpha(128);  // 50% transparent

其中INT的范围从0(完全透明)到255(完全不透明)。

其他回答

从上面看就简单多了。 默认的alpha属性是按钮

android:alpha="0.5"

范围是0表示完全透明,1表示完全不透明。

android:background="@android:color/transparent"

以上是我所知道的… 我认为创建一个自定义按钮类是最好的主意

API等级11 最近我遇到了这个android:alpha xml属性,它的值在0到1之间。相应的方法是setAlpha(float)。

我刚刚发现你的问题,而有类似的问题与TextView。我能够解决它,通过扩展TextView和覆盖onSetAlpha。也许你可以在你的按钮上尝试类似的东西:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class AlphaTextView extends TextView {

  public AlphaTextView(Context context) {
    super(context);
  }

  public AlphaTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public AlphaTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  @Override
  public boolean onSetAlpha(int alpha) {
    setTextColor(getTextColors().withAlpha(alpha));
    setHintTextColor(getHintTextColors().withAlpha(alpha));
    setLinkTextColor(getLinkTextColors().withAlpha(alpha));
    return true;
  }
}

对于API < 11的textView颜色,我做了以下工作:

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

有点麻烦,但嘿,它工作:-)

如果你使用Kotlin,像这样设置alpha很容易

imageView.alpha= 0.5F

其中值必须为浮点数。