Reputation: 421
I want to add ripple effect on my recycler view item,android:background="?android:attr/selectableItemBackground"
I am able to aceive the ripple effect but the problem is i want to have ripple effect on white background. Here is my 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>
I can not have two android backgrounds so how can i achieve ripple effect on white background
Upvotes: 4
Views: 6228
Reputation: 369
In the layout for the recycler item view use foreground and background
<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>
Then use the code below (from Aniket Jadhav) in the constructor of your RecyclerViewItemViewHolder (but with getForeground instead of 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);
}
Upvotes: 0
Reputation: 166
You can use RippleDrawable
class for this. Below is the code :
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);
If you are comfortable with xml you can use the below code :
<?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>
Upvotes: 4