Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding the effects of a RippleDrawable and a StateListDrawable to a RecyclerView

I'm working on an app that uses a dual-pane layout on larger devices similar to what's detailed here. A summary of the layout; one pane contains a list of options while the other will display detailed information on an option selected from the other pane.

Right now when an option is selected there is the ripple effect that's seen when selecting other elements (buttons, check boxes, etc) but after the animation completes the element returns to it's previous color. I'd like to retain the highlight from the ripple after the animation completes and I'm having trouble figuring out how to accomplish this.

This is how my ripple background currently looks. The focus selector doesn't do anything - couldn't figure out how to actually give the elements focus. I've also tried using a selected selector but that happens immediately, overriding the ripple.

<?xml version="1.0" encoding="utf-8"?>
    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:colorAccent">
    <item android:id="@android:id/mask"
        android:drawable="@android:color/black" />
    <item>
        <selector>
            <item android:state_focused="true"
                android:drawable="@color/accent" />
        </selector>
    </item>
</ripple>

To re-iterate, my question is this: Is it possible to have both a ripple effect followed by a highlighted selection, and if so how?

like image 980
Ryan Durel Avatar asked Nov 10 '22 22:11

Ryan Durel


1 Answers

This has preserved the ripple animation for me on selection.

With your ripple drawable use:

<?xml version="1.0" encoding="utf-8"?>
    <item>
        <selector>
            <item android:state_selected="true"
                  android:drawable="@color/selected_color" />
            <item android:drawable="@color/normal_color" />
        </selector>
    </item>
</ripple>

On your adapter, call setHasStableIds(true) and implement getItemId to return unique values representing your rows.

When an item is selected, do:

ViewHolder oldViewHolder = (ViewHolder) recyclerView.findViewHolderForItemId(oldItemId);
oldViewHolder.itemView.setSelected(false);

ViewHolder newViewHolder = (ViewHolder) recyclerView.findViewHolderForItemId(newItemId);
newViewHolder.itemView.setSelected(true);

Also in your Adapter:

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {

    ...

    viewHolder.itemView.setSelected(isSelected);

    ...
}

On a side note, the focused selector is used for highlighting navigation on devices that use a d-pad like TV and some older phones.

like image 91
Andy McSherry Avatar answered Nov 14 '22 21:11

Andy McSherry