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 文件?

4

3 回答 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>
于 2013-11-21T12:33:04.750 回答
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>
于 2014-11-21T08:21:06.800 回答
0

选择器 XML 中的项目顺序会有所不同。第一个匹配是要显示的内容。正如您在marmor的回答中看到的那样,按钮的正常状态列在最后。

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

于 2014-06-17T17:10:11.833 回答