Search code examples
androidandroid-recyclerviewbackground-color

Recyclerview Setting BackGround of Item


I have a simple horizontal recyclerview. As the user scrolls, the current item looses focus has background set to transparent and the new focused item is to have its background color changed to green. I have a simple method that takes in the focused position, changes it's color and sets the reset of the items to transparent.

public void resetRecycleColor(int rowindex){
        for(int i=0; i < mRecyclerView.getAdapter().getItemCount(); i++){
            if(i== this.rowindex){
                Log.v("SCROLLS ", "COLOR GREEN "+ i);
               mRecyclerView.getLayoutManager().findViewByPosition(i).setBackgroundColor(Color.GREEN);

            }else{
                Log.v("SCROLLS ", "COLOR TRANSPARENT "+i );
               mRecyclerView.getLayoutManager().findViewByPosition(i).setBackgroundResource(R.color.gridBackgroundBlack);
                }
        }
    }

Am I attempting to change the item background correctly? Something is wrong because it crashes on the line where the color is set. Comment out those lines and scrolling works fine. Can somebody point out why the crash may occur? Thanks


Solution

  • You don't seem to understand the ViewHolder pattern.

    You only have enough views (plus about 2) to fill RecyclerView. For example if you have 2000 items but they are represented in list that shows 3 items each, you only have 5 ViewHolders created. That way when scrolling views that exit the screen, reenter from the other side but displayed values are changed (in OnBindViewHolder).

    Crash is occurring in findViewByPosition(i) since you're trying to get views for entire list but you only have views for a few of them, so this returns null.

    I don't understand your use case entirely, but if you're repeatedly calling your method during onScroll then it has really bad performance, cleaner solution would be modifying your adapters onBindViewHolder to properly modify focused view and calling notifyItemChanged() to trigger rebinds on new/old focused view.