棒棒糖涟漪Drawable与Pre-Lollipop的选择器的比较

38

我有不同draw9patch png作为背景的按钮。 目前,这些按钮由类似于以下内容的selector控制:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/pressed" android:state_pressed="true"/>
  <item android:drawable="@drawable/disabled" android:state_enabled="false"/>
  <item android:drawable="@drawable/focused" android:state_focused="true"/>
  <item android:drawable="@drawable/default"/>
</selector>

对于Android Lollipop,他们有一个RippleDrawable用于触摸效果,大致如下:

<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="?android:colorControlHighlight">
    <item>
    ...
    </item>
</ripple>

关于新的触摸波纹效果:

1:我能将draw9patch设置为RippleDrawable的背景吗?

2:我要如何适应上述两种不同的 XML,以符合 Material design 的要求?我是否需要为新的RippleDrawable另外创建一个文件夹或布局 XML?


我认为你不能将9png应用为背景。 你可以将颜色应用于你的rippleDrawable。 - Gabriele Mariotti
1个回答

78
是的。有关RippleDrawable的详细信息,请参阅文档,了解层如何合成,但基本上您需要:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:attr/colorControlHighlight">
    <item android:drawable="@drawable/yourninepatch" />
</ripple>

或者为了以更清晰的方式处理禁用状态,您可能想要:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:attr/colorControlHighlight">
    <item>
        <selector>
            <item android:state_enabled="false">
                <nine-patch
                    android:src="@drawable/yourninepatch"
                    android:alpha="?android:attr/disabledAlpha" />
            </item>
            <item>
                <nine-patch android:src="@drawable/yourninepatch" />
            </item>
        </selector>
    </item>
</ripple>

2) 是的,你应该将ripple XML文件放置在drawable-v21目录下。


1
抱歉,我是指drawable-v21目录。 - alanv
1
有没有什么办法可以自动地应用到所有的drawable上?这样我们就不必遭受复制和粘贴的痛苦了吗? - Rafael Sanches
你可以编写一个脚本来完成它,但是你可能需要重新考虑一下为什么有这么多需要前景涟漪反馈的自定义可绘制对象。通常情况下,你只会在按钮上使用它。 - alanv
1
请再次阅读答案和评论。它应该放在drawable-v21中。 - alanv
2
不,你只需要一个涟漪元素。通常情况下,你会将其保留为默认的colorControlHighlight值,但如果你绝对需要在按下和聚焦时具有不同的涟漪颜色,你也可以将颜色设置为颜色状态列表。请记住,只有当项目启用并按下或聚焦时才会看到涟漪效果。 - alanv
显示剩余6条评论

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