Change Ripple Color programmatically according to background

546 Views Asked by At

I've a recyclerview adapter that changes the entire row background color upon a condition. The row is clickable and has android:background="?attr/selectableItemBackground" set. Now, if I change the color (e.g. green), I lose the ripple effect. How can I set it programmatically? I need a white ripple in my case with green bg.

if (dish.isSelected()) {
    // GREEN BACKGROUND NOT WORKING (NO RIPPLE AT ALL)
    TypedValue typedValue = new TypedValue();
    context.getTheme().resolveAttribute(R.attr.selectableItemBackground, typedValue, true);
    viewHolderDish.itemView.setBackgroundResource(typedValue.resourceId);
    viewHolderDish.itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.green));
    viewHolderDish.itemView.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.green)));
} else {
    // TRANSPARENT BACKGROUND WORKS
    TypedValue typedValue = new TypedValue();
    context.getTheme().resolveAttribute(R.attr.selectableItemBackground, typedValue, true);
    viewHolderDish.itemView.setBackgroundResource(typedValue.resourceId);
    viewHolderDish.itemView.setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent));
}
1

There are 1 best solutions below

0
Jumpa On BEST ANSWER

Solved setting this as background drawable:

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@android:color/white">
    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <solid android:color="@color/green" />
        </shape>
    </item>
    <item
        android:id="@android:id/mask"
        android:drawable="@android:color/white" />
</ripple>