XML中的涟漪可绘制元素无法正常工作。

4

我遇到了一个问题:我有一个xml drawable,我想将其用作单选按钮的背景,但涟漪效果不起作用。有人可以帮助我吗?

我的背景xml代码:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#8bc34a" >
<item>
   <selector>
   <item android:drawable="@drawable/tb_checked" android:state_checked="true"></item>
<item android:drawable="@drawable/transparent"></item>
</selector>
</item>
</ripple>

1
阅读RippleDrawable文档。涟漪会在内容上进行屏蔽。当未选中时,您的内容是透明的。 - alanv
@alanv 那我该怎么修复它呢?我需要在我的项目标签中添加 android:id="@android:id/mask" 吗? - Simeon Schaub
这取决于您想要实现什么效果。您现在拥有的规定了未选中时没有背景,选中时在 @drawable/tb_checked 之上绘制涟漪。 - alanv
@alanv 我希望在单选按钮被选中时,tb_checked成为我的背景,但我也希望在按下或选择时有涟漪效果。 - Simeon Schaub
3个回答

7
如果您想在其他内容上方或下方显示一个无限波纹,则使用<layer-list>容器进行堆叠,不要将任何内容放置在<ripple>元素内。
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <ripple android:color="#8bc34a" />
    </item>
    <item>
        <selector>
            <item android:drawable="@drawable/tb_checked"
                  android:state_checked="true" />
            <item android:drawable="@drawable/transparent" />
        </selector>
    </item>
</layer-list>

谢谢你的回答!现在对于按钮它可以正常工作了,但是对于单选按钮仍然没有涟漪效果。你知道如何修复这个问题吗? - Simeon Schaub
你是在RadioButton上使用setBackground()还是setButtonDrawable()?后者不支持投影(无界)涟漪。 - alanv
我正在使用android:background属性在XML中完成它。 - Simeon Schaub
我有同样的问题。它适用于按钮,但不适用于单选按钮。 - Andranik
如果您只想要一个透明的背景,那么这个方法非常完美。在这种情况下,<item><selector><item(s)> 可以被一个单独的透明 drawable <icon> 标签所替代。但是,水波纹的性能会受到极大的影响。 - Daniel F
显示剩余2条评论

1
<RadioButton
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:padding="@dimen/activity_horizontal_margin"
    android:text="Choice 1"
    android:gravity="center"
    android:background="@drawable/button_choice_white"
    android:button="@null"/>

在v1-drawable中添加具有涟漪效果的背景drawable。
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorControlHighlight">
<item android:id="@android:id/mask">
    <shape android:shape="rectangle">
        <solid android:color="?attr/colorAccent" />
    </shape>
</item>
<item>
    <selector>
        <item android:state_pressed="true">
            <shape android:shape="rectangle">
                <solid android:color="?attr/colorAccent"/>
            </shape>
        </item>

        <item android:state_checked="true">
            <shape android:shape="rectangle">
                <solid android:color="?attr/colorAccent"/>
            </shape>
        </item>

        <item>
            <shape android:shape="rectangle">
                <solid android:color="@color/button_choice_background"/>
            </shape>
        </item>
    </selector>
</item>


-1
在RadioButton的xml声明中添加以下属性:android:background="?android:selectableItemBackground"。我非常确定这会起作用。

这不是我真正想要的。我想要一个具有向后兼容性的定制背景。但还是谢谢你的回答! - Simeon Schaub

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