Antony Mathews
Antony Mathews

Reputation: 17

Repetition of recyclerview row property after a certain number of rows?

I was creating a navigation drawer with recyclerview , then a need to highlight the selected/clicked row of the recyclerview. I put .setBackgroundColor(Color.GRAY) inside the addOnItemTouchListener. It works but the background color property repeat after a certain number of rows ... how do i resolve it?? thanks in advance...

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if(child != null && gestureDetector.onTouchEvent(e)) {
                int position = rv.getChildAdapterPosition(child);
                DrawerItem model = mDrawerItemList.get(position);
                child.setBackgroundColor(Color.GRAY);
                drawerLayout.closeDrawers();
       Toast.makeText(RecyclerNavigationActivity.this,String.valueOf(position),Toast.LENGTH_SHORT).show();
            }

            return false;
        }

Upvotes: 2

Views: 193

Answers (1)

pawelo
pawelo

Reputation: 1415

You shouldn't touch RecyclerView's child views from outside onBindViewHolder() unless you know exactly what you are doing. RecyclerView is trying to reuse layouts that are no longer visible, that's why if you change color of one item and don't change it back when reusing layout, changed color will persist.

What you need to do, is to attach OnClickListener to ViewHolder and update its background in onBindViewHolder() method.

public class YourAdapter extends RecyclerViewAdapter {

    ...

    int selectedItem = -1;

    public void setSelectedItem(int item) {
        this.selectedItem = i;
        this.notifyItemChanged(selectedItem);
    }

    @Override
    onBindViewHolder(ViewHolder holder, int position) {

        ... // other stuff here

        if (position == selectedItem) {
            holder.layout.setBackgroundColor(Color.GRAY);
        } else {
            holder.layout.setBackgroundColor(Color.WHITE);
        }
    }
}

Upvotes: 3

Related Questions