增加波纹背景影响在白色背景

时间:2017-03-25 12:31:30

标签: android

我想在我的回收商视图项android:background="?android:attr/selectableItemBackground" 上添加涟漪效果我能够产生涟漪效应,但问题是我想在白色背景上产生涟漪效应。这是我的xml。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:background="?android:attr/selectableItemBackground"
android:background="@color/white"
android:layout_marginBottom="1dp"
xmlns:tools="http://schemas.android.com/tools"
tools:background="@color/white"
android:padding="6dp">...
.....SOME MORE CODE....
</LinearLayout>

我不能拥有两个android背景,所以我怎样才能在白色背景上实现涟漪效果

3 个答案:

答案 0 :(得分:2)

您可以使用RippleDrawable类。以下是代码:

RippleDrawable rippleDrawable = (RippleDrawable)view.getBackground(); // It will assume bg is a RippleDrawable

int[][] states = new int[][] { new int[] { android.R.attr.state_enabled} };
int[] colors = new int[] { Color.BLUE }; // sets the ripple color to blue

ColorStateList colorStateList = new ColorStateList(states, colors);
rippleDrawable.setColor(colorStateList);

如果您对xml感到满意,可以使用以下代码:

<?xml version="1.0" encoding="utf-8"?>
<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#FF000000"> 

    <!-- the normal bg color -->
    <item>
        <color android:color="#FFDDDDAA" />
    </item>

    <!-- make sure the ripple doesn't exceed the bounds -->
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="?android:colorAccent" />
        </shape>
    </item>
</ripple>

答案 1 :(得分:1)

使用:

android:foreground="?android:attr/selectableItemBackground"

答案 2 :(得分:0)

在回收项目视图的布局中,使用前景和背景

<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:background="@android:color/white"
android:foreground="?android:attr/selectableItemBackground">
.....SOME MORE XML.....
</ConstraintLayout>

然后在RecyclerViewItemViewHolder的构造函数中使用下面的代码(来自Aniket Jadhav)(但使用getForeground而不是getBackground)

public RecyclerViewItemViewHolder(View view) {
    super(view);
    mView = view;

    android.graphics.drawable.RippleDrawable rippleDrawable = (android.graphics.drawable.RippleDrawable)view.getForeground();

    int[][] states = new int[][] { new int[] { android.R.attr.state_enabled} };
    int[] colors = new int[] { Color.GRAY };

    android.content.res.ColorStateList colorStateList = new android.content.res.ColorStateList(states, colors);
    rippleDrawable.setColor(colorStateList);
}
相关问题