代码之家  ›  专栏  ›  技术社区  ›  Florian Walther

自定义按钮-为什么一个带有png图像的StateListDrawable去掉了默认的按钮StateListAnimator,而xml形状保留了它?

  •  0
  • Florian Walther  · 技术社区  · 6 年前

    我在玩弄习俗 Buttons 通过在 StateListDrawable Button . AppCompatButton 行为(拉起动画、阴影等)被停用,只留下不同状态的普通图像。 但当我用同样的方法 状态列表可绘制 对于xml形状(示例位于底部),它保持默认值 按钮 行为。为什么?

    状态列表可提取:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@drawable/button_pressed" />
    <item
        android:state_enabled="false"
        android:drawable="@drawable/button_disabled" />
    <item
        android:drawable="@drawable/button_default" />
    </selector>
    

    xml形状示例:

    <?xml version="1.0" encoding="utf-8"?>
    
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
        <gradient
            android:startColor="#00CCFF"
            android:centerColor="#0000CC"
            android:endColor="#00CCFF"
            android:angle="90"/>
        <padding android:left="7dp"
            android:top="7dp"
            android:right="7dp"
            android:bottom="7dp" />
        <stroke
            android:width="2dip"
            android:color="#FFFFFF" />
        <corners android:radius= "15dp" />
    </shape>
    

    截图:

    为了测试的目的,我只是把启动器图标的背景作为按钮图像。 你可以看到,如果我选择启动程序图像作为背景,按钮会丢失它的阴影和上拉动画。但是当我使用一个XML形状作为背景时,它将两者都保留下来。

    Button with Launcher Icon Background

    Button with XML Shape Background

    1 回复  |  直到 6 年前
        1
  •  0
  •   Fatih    6 年前

    这些行为不会被停用。它们只是隐藏在您创建的xml drawable下面。由于您创建的自定义绘图文件的大小没有限制,因此它将填充由其父布局定义的所有可能的区域。换句话说,它匹配父对象( "match_parent" ). 所以你看不见。

    另一方面,PNG文件有精确的尺寸,并且没有覆盖父布局的整个区域,所以还有一些空间可以让你看到效果和动画,比如阴影。为了能够看到带有定制xml的动画,我建议您提供一些 padding 设置自定义xml作为背景时。或者你可以用它作为 "wrap_content" 而不是 “匹配父项” .