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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2838757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:34:34  来源:igfitidea点击:

How to Set Opacity (Alpha) for View in Android

androidbuttonviewopacity

提问by ncakmak

I have a button as in the following:

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

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

In my onCreate()event, I am calling Button01 like this:

在我的onCreate()活动中,我像这样调用 Button01:

setContentView(R.layout.main);

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

There is a background in the application, and I want to set an opacity on this submit button. How can I set an opacity for this view? Is it something that I can set on the java side, or can I set in the main.xml file?

应用中有一个背景,我想在这个提交按钮上设置一个不透明度。如何为此视图设置不透明度?它是我可以在 java 端设置的东西,还是可以在 main.xml 文件中设置?

On the java side I tried Button01.mutate().SetAlpha(100), but it gave me an error.

在 Java 方面我尝试过Button01.mutate().SetAlpha(100),但它给了我一个错误。

采纳答案by RoToRa

I just found your question while having the similar problem with a TextView. I was able to solve it, by extending TextView and overriding onSetAlpha. Maybe you could try something similar with your button:

我刚刚在 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;
  }
}

回答by Jake Wilson

I'm amazed by everyone else's MUCHmore complicated answers.

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

XML

XML

You can very simply define the alpha in the color definition of the button (or any other view) in your xml:

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

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

In the above example, the color would be a partially transparent red.

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

When defining the color of a view, the format can be either #RRGGBBor #AARRGGBB, where AAis the hex alpha value. FFwould be fully opaque and 00would be full transparent.

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

Dynamically

动态地

If you need to dynamically alter the opacity in your code, use

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

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

Where the INT ranges from 0(fully transparent) to 255(fully opaque).

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

回答by abhi

I guess you may have already found the answer, but if not (and for other developers), you can do it like this:

我想您可能已经找到了答案,但如果没有(对于其他开发人员),您可以这样做:

btnMybutton.getBackground().setAlpha(45);

Here I have set the opacity to 45. You can basically set it from anything between 0(fully transparent) to 255(completely opaque)

在这里,我将不透明度设置为 45。您基本上可以将其设置为0(完全透明)到255(完全不透明)之间的任何

回答by Akos Cz

What I would suggest you do is create a custom ARGB colorin your colors.xml file such as :

我建议你做的是在你的 colors.xml 文件中创建一个自定义的ARGB 颜色,例如:

<resources>
<color name="translucent_black">#80000000</color>
</resources>

then set your button background to that color :

然后将您的按钮背景设置为该颜色:

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

Another thing you can do if you want to play around with the shape of the button is to create a Shape drawable resourcewhere you set up the properties what the button should look like :

如果您想改变按钮的形状,您可以做的另一件事是创建一个Shape 可绘制资源,您可以在其中设置按钮的外观:

file: res/drawable/rounded_corner_box.xml

文件:res/drawable/rounded_corner_box.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#80000000"
        android:endColor="#80FFFFFF"
        android:angle="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

Then use that as the button background :

然后将其用作按钮背景:

    android:background="@drawable/rounded_corner_box"

回答by cange1

According to the android docs view alpha is a value between 0 and 1. So to set it use something like this:

根据 android docs 视图,alpha 是一个介于 0 和 1 之间的值。因此要设置它,请使用以下内容:

View v;
v.setAlpha(.5f);

回答by Raja Jawahar

Much more easier from the above. Default alpha attribute is there for button

从上面讲要容易得多。按钮有默认的 alpha 属性

android:alpha="0.5"

The range is between 0 for complete transparent and 1 for complete opacity.

范围介于 0 表示完全透明和 1 表示完全不透明之间。

回答by Josnidhin

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

The above is something that I know... I think creating a custom button class is the best idea

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

API Level 11
Recently I came across this android:alphaxml attribute which takes a value between 0 and 1. The corresponding method is setAlpha(float).

API Level 11
最近我遇到了这个android:alphaxml 属性,它的值介于 0 和 1 之间。相应的方法是setAlpha(float)

回答by Hesam

Although btnMybutton.getBackground().setAlpha(45);is nice idea, it just apply alpha to background and not the whole view.

虽然btnMybutton.getBackground().setAlpha(45);是个好主意,但它只是将 alpha 应用于背景而不是整个视图。

If you want apply alpha to view use btnMybutton.setAlpha(0.30f);instead. This apply opacity to View. It accepts a value between 0 and 1.

如果你想应用 alpha 来查看使用btnMybutton.setAlpha(0.30f);。这将不透明度应用于视图。它接受一个介于 0 和 1 之间的值。

Doc says:

Doc 说:

Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque. If this view overrides onSetAlpha(int) to return true, then this view is responsible for applying the opacity itself. Otherwise, calling this method is equivalent to calling setLayerType(int, android.graphics.Paint) and setting a hardware layer. Note that setting alpha to a translucent value (0 < alpha < 1) may have performance implications. It is generally best to use the alpha property sparingly and transiently, as in the case of fading animations.

设置视图的不透明度。这是一个从 0 到 1 的值,其中 0 表示视图完全透明,1 表示视图完全不透明。如果此视图覆盖 onSetAlpha(int) 以返回 true,则此视图负责应用不透明度本身。否则,调用该方法就相当于调用了 setLayerType(int, android.graphics.Paint) 并设置了一个硬件层。请注意,将 alpha 设置为半透明值 (0 < alpha < 1) 可能会影响性能。通常最好少用且短暂地使用 alpha 属性,就像在淡入淡出动画的情况下一样。

回答by Palash Dange

For a view you can set opacity by the following.

对于视图,您可以通过以下方式设置不透明度。

view_name.setAlpha(float_value);

The property view.setAlpha(int)is deprecated for the API version greater than 11. Henceforth, property like .setAlpha(0.5f)is used.

view.setAlpha(int)对于大于 11 的 API 版本,不推荐使用该属性。此后,使用属性 like .setAlpha(0.5f)

回答by annie

I've run into this problem with ICS/JB because the default buttons for the Holo theme consist of images that are slightly transparent. For a background this is especially noticeable.

我在使用 ICS/JB 时遇到了这个问题,因为 Holo 主题的默认按钮由略微透明的图像组成。对于背景,这一点尤其明显。

Gingerbread vs. ICS+:

姜饼与 ICS+:

GingerbreadICS

姜饼ICS

Copying over all of the drawable states and images for each resolution and making the transparent images solid is a pain, so I've opted for a dirtier solution: wrap the button in a holder that has a white background. Here's a crude XML drawable (ButtonHolder) which does exactly that:

复制每个分辨率的所有可绘制状态和图像并使透明图像变得坚实是一种痛苦,所以我选择了一个更脏的解决方案:将按钮包裹在具有白色背景的支架中。这是一个粗略的 XML drawable (ButtonHolder),它正是这样做的:

Your XML file

您的 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              style="@style/Content">
  <RelativeLayout style="@style/ButtonHolder">
      <Button android:id="@+id/myButton"
              style="@style/Button"
              android:text="@string/proceed"/>
    </RelativeLayout>
</LinearLayout>

ButtonHolder.xml

ButtonHolder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="rectangle">
      <solid android:color="@color/white"/>
    </shape>
  </item>

</layer-list>

styles.xml

样式文件

.
.
.      
  <style name="ButtonHolder">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:background">@drawable/buttonholder</item>
  </style>

  <style name="Button" parent="@android:style/Widget.Button">
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:textStyle">bold</item>
  </style>
.
.
.

However, this results in a white border because the Holo button images include margins to account for the pressed space:

但是,这会导致白色边框,因为 Holo 按钮图像包含用于说明按下空间的边距:

Too much whiteToo much white pressed

太白了压得太白了

So the solution is to give the white background a margin (4dp worked for me) and rounded corners (2dp) to completely hide the white yet make the button solid:

所以解决方案是给白色背景一个边距(4dp 对我有用)和圆角(2dp)以完全隐藏白色但使按钮固定:

ButtonHolder.xml

ButtonHolder.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

  <item>
    <shape android:shape="rectangle">
      <solid android:color="@android:color/transparent"/>
    </shape>
  </item>

  <item android:top="4dp" android:bottom="4dp" android:left="4dp" android:right="4dp">
    <shape android:shape="rectangle">
      <solid android:color="@color/white"/>
      <corners android:radius="2dp" />
    </shape>
  </item>

</layer-list>

The final result looks like this:

最终结果如下所示:

No whiteNo white pressed

没有白色无白压

You should target this style for v14+, and tweak or exclude it for Gingerbread/Honeycomb because their native button image sizes are different from ICS and JB's (e.g. this exact style behind a Gingerbread button results in a small bit of white below the button).

您应该针对 v14+ 使用这种样式,并针对 Gingerbread/Honeycomb 调整或排除它,因为它们的原生按钮图像大小与 ICS 和 JB 的不同(例如,Gingerbread 按钮后面的这种确切样式会导致按钮下方有一点白色)。