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

2023-09-11 11:42:11 作者:我好脆弱

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

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>

在我的的onCreate()事件,我打电话Button01是这样的:

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

setContentView(R.layout.main);

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

有一个在应用程序的背景下,我想设置这个提交按钮的不透明度。如何设置不透明度为这个观点?有什么事情,我可以在Java端设置,或者我可以在main.xml中文件中设置?

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方面我试过 Button01.mutate()。SetAlpha(100),但它给了我一个错误。

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

推荐答案

我刚刚发现你的问题,而具有类似的问题,一个TextView。我能解决这个问题,通过扩展的TextView并覆盖 onSetAlpha 。也许你可以尝试类似的东西与你的按钮:

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:

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;
  }
}