简体   繁体   中英

Ripple effect on ListView items

I created a custom list item that I put into a ListView. These items are clickable (single & multiple choices) and once clicked I want them to change the color without loosing the nice Material ripple effect.

That's the static way of just changing the color once togglet:

public class CustomListItem extends LinearLayout implements Checkable {
    public CustomListItem(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomListItem(Context context) {
        super(context);
    }

    private boolean checked = false;
    private TextView textView;

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        textView = (TextView) findViewById(R.id.listViewText);
    }

    @Override
    public void setChecked(boolean checked) {
        this.checked = checked;
        int color = checked ? R.color.colorAccent : R.color.appWhite;
        textView.setBackgroundColor(ContextCompat.getColor(getContext(), color));
    }

    @Override
    public boolean isChecked() {
        return checked;
   }

    @Override
    public void toggle() {
        setChecked(!checked);
    }
}

I also created my own ripple drawable so that I can change the color without loosing the ripple effect - however that way the color of the item remains the same/doesn't change.

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?attr/colorControlHighlight">
    <item android:drawable="?attr/colorAccent" />
</ripple>

In short: I want my list items to change from background color x to y when clicked and back from y to x but still having the ripple effect on them.

Help is very much appreciated, thanks!

I know you already found a solution, but here is what worked for me just yesterday:

You don't need to define your own ripple drawable. Just do this on your parent ListView:

<ListView
    ...
    android:drawSelectorOnTop="true"/>

This will handle the ripple effect for you so you only need to take care of updating the color (which you are already doing) of your custom list item on item click.

Try with the selectableItemBackground attribute.

android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM