更改按钮背景颜色与波纹

时间:2017-08-13 12:49:35

标签: android android-layout android-view android-theme android-styles

在我的styles.xml文件中添加了这段代码,将按钮的主要颜色更改为绿色,即colorPrimary。

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.Button" parent="Base.Widget.AppCompat.Button">
    <item name="colorButtonNormal">@color/colorPrimary</item>
</style>

</resources>

然后我尝试将它与涟漪效果结合起来,因为我在另一个堆栈帖子中读到你需要创建一个ripple_effect xml文件并将其用作按钮的背景。然后将按钮的样式设置为style.xml中详细说明的自定义样式。

我如何链接到编辑器中的按钮

enter image description here

我做错了什么。是否有更简单的方法来实现为按钮和颜色添加涟漪效果。我一直试图通过堆栈溢出帖子解决这个问题,但每个解决方案似乎都不同。我在API 23上。

2 个答案:

答案 0 :(得分:1)

可以使用ThemeOverlay来实现。

res/values/themes.xml

中有这个
<style name="GreenButtonTheme" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorButtonNormal">@color/green</item>
</style>

在你的xml中:

<Button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Button"
  android:theme="@style/GreenButtonTheme" />

然后你会得到这个输出:

enter image description here

有关详细信息,请参阅this article

答案 1 :(得分:0)

您可以使用setColorFilter():

btn.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
相关问题