按钮不透明度/透明度

8

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     android:background="@drawable/background"
        android:gravity="center"
        android:color="#66FF0000"

    >


    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/noua"
        android:textStyle="bold"
        android:textColor="#808080"
         />


    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/zece"
        android:textStyle="bold"
        android:textColor="#808080" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/unspe"
        android:textStyle="bold"
        android:textColor="#808080" />

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/doispe"
        android:textStyle="bold"
        android:textColor="#808080"
/>

</LinearLayout>

这是我的main.xml文件,我想让按钮尽可能透明,但仍然要看得到它们,我不知道在哪里添加什么内容,请在xml中使用低透明度来更正。非常感谢:D
3个回答

22

请查看如何在Android中设置View的透明度(Alpha)

您可以通过使用 #XX808080 的形式来设置对象背景的透明度,其中 XX 代表 alpha/透明度值。

android:background="#80FF0000"

这将是一个半透明的红色背景。

您可以使用相同的方式,通过textColor属性来设置按钮文本的透明度:

android:textColor="#80FF0000"

你也可以通过代码实现动画效果。

AlphaAnimation alphaAnim = new AlphaAnimation(1.0f, 0.5f);
alphaAnim.setDuration (400);
myButton.getBackground().startAnimation(alphaAnim);  // set alpha on background

或者直接:

myButton.getBackground().setAlpha(0.5f);   // added in API 11, sets alpha on background

两种方法都将alpha设置为50%。

最后,您可以尝试在XML中添加android:alpha:

<Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/zece"
        android:textStyle="bold"
        android:textColor="#808080" 
android:alpha="0.5"
/>

1

您可能无法通过代码更改它们的不透明度,因为它们是9patch图案。您需要创建自己的9patch图案,并将其设置为按钮的背景。如果您想要纯色,当然也可以使用类似以下的内容:

android:background="#80363636"

这里的 #AARRGGBB,如果你将前两位数字保持较低的值,就会得到相应的不透明度。

1
在代码中,您可以获取按钮的实例并手动设置背景可绘制对象的透明度。
 Button btn = (Button) findViewById(..);
 btn.getBackground().setAlpha( a );  // where a : 0..255 : 0=transparent, 255=fully opaque

我认为您无法在xml文件中设置alpha。没有可允许此操作的drawable资源[请参见http://developer.android.com/guide/topics/resources/drawable-resource.html]。您必须在代码中设置alpha或创建自己的半透明背景drawable并使用它。 - dangVarmit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接