如何在Android中为View设置不透明度(Alpha)

如何在Android中为View设置不透明度(Alpha)

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

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


倚天杖
浏览 3709回答 3
3回答

慕哥9229398

我刚发现你的问题,同时遇到与TextView类似的问题。通过扩展TextView和覆盖,我能够解决它onSetAlpha。也许你可以试试类似你的按钮:import&nbsp;android.content.Context;import&nbsp;android.util.AttributeSet;import&nbsp;android.widget.TextView;public&nbsp;class&nbsp;AlphaTextView&nbsp;extends&nbsp;TextView&nbsp;{ &nbsp;&nbsp;public&nbsp;AlphaTextView(Context&nbsp;context)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;super(context); &nbsp;&nbsp;} &nbsp;&nbsp;public&nbsp;AlphaTextView(Context&nbsp;context,&nbsp;AttributeSet&nbsp;attrs)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;super(context,&nbsp;attrs); &nbsp;&nbsp;} &nbsp;&nbsp;public&nbsp;AlphaTextView(Context&nbsp;context,&nbsp;AttributeSet&nbsp;attrs,&nbsp;int&nbsp;defStyle)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;super(context,&nbsp;attrs,&nbsp;defStyle); &nbsp;&nbsp;} &nbsp;&nbsp;@Override &nbsp;&nbsp;public&nbsp;boolean&nbsp;onSetAlpha(int&nbsp;alpha)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;setTextColor(getTextColors().withAlpha(alpha)); &nbsp;&nbsp;&nbsp;&nbsp;setHintTextColor(getHintTextColors().withAlpha(alpha)); &nbsp;&nbsp;&nbsp;&nbsp;setLinkTextColor(getLinkTextColors().withAlpha(alpha)); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;true; &nbsp;&nbsp;}}

不负相思意

我对每个人都感到惊讶别人的MUCH更复杂的答案。XML您可以非常简单地在xml中按钮(或任何其他视图)的颜色定义中定义alpha:android:color="#66FF0000"&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Partially&nbsp;transparent&nbsp;red在上面的例子中,颜色是部分透明的红色。定义视图的颜色时,格式可以是#RRGGBB或#AARRGGBB,其中AA是十六进制alpha值。FF将完全不透明并且00完全透明。动态如果需要动态更改代码中的不透明度,请使用myButton.getBackground().setAlpha(128);&nbsp;&nbsp;//&nbsp;50%&nbsp;transparentINT的范围从0(完全透明)到255(完全不透明)。
打开App,查看更多内容
随时随地看视频慕课网APP