我看到了一些 SO 问题,他们提供了一些可能的方法来实现我想要的。例如:
在styles.xml中使用
colorControlHighlight
属性。这是我的样式-v21.xml:
<style name="SelectableItemBackground"> <item name="android:colorControlHighlight">#5677FC</item> <item name="android:background">?attr/selectableItemBackground</item> </style>
还有我的小部件:
<TextView android:id="@+id/tv_take_photo_as_bt" android:layout_width="280dp" android:layout_height="48dp" android:text="@string/act_take_photo" style="@style/SelectableItemBackground"/>
而且它不起作用。我也尝试将
parent="Theme.AppCompat
添加到“SelectableItemBackground”样式,或者改成colorControlHighlight(no android: prefix)"
,或者改成? android:attr/selectableItemBackground
,两个都没用。在布局中使用
backgroundTint
属性。所以我将
android:backgroundTint="#5677FC"
添加到我的TextView
中。还是没用。然后我尝试将android:backgroundTintMode
改为src_in
和src_atop
,它们都没有任何区别。
那么,当我使用 ?attr/selectableItemBackground
作为背景时,如何更改波纹颜色。我只关注 Lollipop 及以上。提前谢谢!
最佳答案
终于找到解决办法了:与其直接在主题SelectableItemBackground
中使用android:colorControlHighlight
,不如写另一种风格:
<style name="SelectableItemTheme">
<item name="colorControlHighlight">@color/ripple_color</item>
</style>
然后:
<style name="SelectableItemBackground">
<item name="android:theme">@style/SelectableItemTheme</item>
<item name="android:background">?attr/selectableItemBackground</item>
</style>
最后将 style="@style/SelectableItemBackground"
添加到 layout.xml 中的 View
中。
2016 年 8 月 26 日更新
在N发布之后,我发现有时候我们不能用这个方法来为某种View
(例如CardView
)设置波纹颜色。现在我强烈推荐开发者使用RippleDrawable
,它也可以在xml中声明。这是一个例子:
我想在用户触摸/点击API21以上的CardView
时显示涟漪效果,当然Lollipop之前应该有另一种反馈。所以我应该写:
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:foreground="@drawable/selectable_item_background"/>
和drawable
文件夹中的selectable_item_background
:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@android:color/transparent" />
<item android:drawable="@color/color_clicked" />
</selector>
selectable_item_background
在 drawable-v21
文件夹中:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ripple_black" />
</selector>
最后,drawable
(或drawable-v21
)文件夹中的ripple_black
:
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:color="@color/color_clicked"
tools:ignore="NewApi" /> <!--you can remove this line if it's in v21 folder-->
就是这样。对于其他 View ,也许您应该使用 android:background="@drawable/selectable_item_background"
。不要忘记为它们设置 OnClickListener
、OnTouchListener
或类似的东西,否则不会显示波纹。
关于android - 使用 ?attr/selectableItemBackground 作为背景时如何修改波纹颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33061050/