可组合 PNG 和叠加层的 XML 可绘制对象

10

我有一个PNG格式的按钮,它处于启用状态且未被按下。当用户单击该按钮时,我只想让PNG变暗。我需要像这样的东西:

  <selector xmlns:android="http://schemas.android.com/apk/res/android" >
  //normal button with background my_button.png
        <item 
            android:state_enabled="true" 
            android:drawable="@drawable/my_button"   //my_button.png
            />
  //pressed button with background my_button.png overlayed by 50% black
        <item 
            android:state_pressed="true"
            android:state_enabled="true"    
            >
            <RelativeLayout 
               android:layout_width="wrap_content"
               android:layout_height="wrap_content">

              <bitmap  android:src="@drawable/my_button"/>
              <color android:color="#00000088"/>
            </RelativeLayout>
        </item>      
    </selector>

有没有什么方法可以做到这一点?还是我必须要有另一个PNG文件?

3个回答

11

在我的 my_button_bg.xml 文件中:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/button_normal"/>
</selector>

button_normal是一张png图片

button_pressed是一个xml文件:

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

其中 btn_bg_pressed_mask 是一个颜色:

<color name="btn_bg_pressed_mask">#19000000</color>

3

这应该可以工作。

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_enabled="true"
        android:drawable="@drawable/my_button" />
    <item>
        <selector>
            <item
                android:state_pressed="true"
                android:state_enabled="true">
                <color android:color="#00000088" />
            </item>
        </selector>
    </item>

</layer-list>

0

选择器XML中项目的顺序会产生影响。第一个匹配项将被显示出来。正如你在marmor的回答中所看到的,按钮的正常状态被列在最后。

另一件需要记住的事情是,如果你使用9-patch图像(.9.png),颜色只会应用于内容区域。因此,如果你希望颜色覆盖整个图像,请确保将整个图像标记为内容区域。


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