使用按钮背景颜色为我的按钮添加波纹效果?

新手上路,请多包涵

我创建了一个按钮,我想为该按钮添加波纹效果!

我创建了一个按钮 bg XML 文件:(bg_btn.xml)

 <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient android:startColor="#FFFFFF" android:endColor="#00FF00" android:angle="270" />
<corners android:radius="3dp" />
<stroke android:width="5px" android:color="#000000" />
</shape>

这是我的涟漪效果文件:(ripple_bg.xml)

 <ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="#f816a463"
    tools:targetApi="lollipop">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#f816a463" />
        </shape>
    </item>
</ripple>

这是我想要添加涟漪效果的按钮:

 <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="173dp"
android:textColor="#fff"
android:background="@drawable/ripple_bg"
android:clickable="true" />

但是添加波纹效果后按钮背景是透明的,而且按钮只有在点击时才会显示,像这样:

点击前

点击时

但是我需要按钮背景颜色和波纹效果,我在 Stack Overflow 的不同博客中找到了一些这样的代码,但仍然无法正常工作!

原文由 rakcode 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 343
2 个回答

对于那些想要将渐变背景、圆角半径和波纹效果加在一起的人来说,这是另一个可绘制的 xml:

 <?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/colorPrimaryDark">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimaryDark" />
            <corners android:radius="@dimen/button_radius_large" />
        </shape>
    </item>

    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <gradient
                android:angle="90"
                android:endColor="@color/colorPrimaryLight"
                android:startColor="@color/colorPrimary"
                android:type="linear" />
            <corners android:radius="@dimen/button_radius_large" />
        </shape>
    </item>
</ripple>

将此添加到按钮的背景中。

 <Button
    ...
    android:background="@drawable/button_background" />

PS:此答案适用于 android api 21 及更高版本。

原文由 Pei 发布,翻译遵循 CC BY-SA 4.0 许可协议

一种简单的方法是设置 此处 概述的视图主题。

_someview.xml

 <ImageView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="?attr/selectableItemBackgroundBorderless"
   android:focusable="true"
   android:src="@drawable/up_arrow"
   android:theme="@style/SomeButtonTheme"/>

_somestyle.xml

 <style name="SomeButtonTheme" >
   <item name="colorControlHighlight">@color/someColor</item>
</style>

原文由 AdamHurwitz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题