3

I have a recycler view, each item in it is represented as a linear layout. I am trying to add ripple effect to each item.

Linear Layout looks something like

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_item"
style="@style/ItemStyle"
android:paddingLeft="6dp"
android:descendantFocusability="blocksDescendants">

ItemStyle in the above layout is given as

<style name="ItemStyle">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:background">@drawable/item_background</item>
    <item name="android:minHeight">@dimen/item_height</item>
    <item name="android:orientation">horizontal</item>
    <item name="android:paddingBottom">1dp</item>
    <item name="android:paddingRight">1dp</item>
</style>

@drawable/item_background is given as

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/primary" />
    <item android:state_activated="true" android:drawable="@color/blue" />
    <item android:drawable="@drawable/item_divider_background" />
</selector>

The problem is that if i change android:background from @drawable/item_background to ?attr/selectableItemBackground, i am able to get the ripple effect but the line divider, @drawable/item_divider_background mentioned inside the @drawable/item_background is not appearing. Can someone tell what is the workaround to add both the divider and the ripple effect.

Haris ali
  • 773
  • 1
  • 13
  • 19
Minions
  • 1,273
  • 1
  • 11
  • 28

1 Answers1

0

One workaround can be to add the divider programmatically using item decorator-

public class MyDecorator extends RecyclerView.ItemDecoration  {
private Drawable mDivider;

public MyDecorator(Context context) {
    mDivider = ContextCompat.getDrawable(context, org.itm.xoinfo.R.drawable.simpleline);
}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
    int left = parent.getPaddingLeft();
    int right = parent.getWidth() - parent.getPaddingRight();

    int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View child = parent.getChildAt(i);

        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

        int top = child.getBottom() + params.bottomMargin;
        int bottom = top + mDivider.getIntrinsicHeight();

        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }
}

}

and adding it like this recyclerView.addItemDecoration(new MyDecorator(this));

and for ripple effect simply add ?attr/selectableItemBackground to the recycler view's layout.

megamind
  • 424
  • 1
  • 4
  • 19