【问题标题】:XML drawable composed of png and overlay由 png 和 overlay 组成的 XML drawable
【发布时间】:2013-01-11 07:18:26
【问题描述】:

我有一个 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 文件?

【问题讨论】:

    标签: android xml button png drawable


    【解决方案1】:

    在 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>
    

    【讨论】:

      【解决方案2】:

      这应该可以工作

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-07-04
          • 2015-11-07
          • 1970-01-01
          • 1970-01-01
          • 2012-07-16
          • 2016-09-25
          • 2016-11-02
          • 1970-01-01
          相关资源
          最近更新 更多