我有一个按钮,如下所示。
<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)
,但它给了我一个错误。
我建议你做的是在你的colors.xml文件中创建一个自定义的ARGB颜色,如::
<resources>
<color name="translucent_black">#80000000</color>
</resources>
然后将你的按钮背景设置为该颜色。
android:background="@android:color/translucent_black"
如果你想改变按钮的形状,还可以创建一个Shape drawable resource,在那里你可以设置按钮的属性。
文件: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>
然后用它作为按钮的背景。
android:background="@drawable/rounded_corner_box"
我刚刚发现了你的问题,同时在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;
}
}
android:background="@android:color/transparent"
以上是我知道的情况...... 我认为创建一个自定义的按钮类是最好的主意
API级别11 最近我遇到了这个android:alphaxml属性,它的取值范围是0到1,对应的方法是setAlpha(float)。