Search code examples
androidandroid-recyclerviewnotifydatasetchanged

Issue refreshing a view of a row in recyclerview


I want to update a view of the recyclerview when a notifyItemChanged has been called. The thing is that I don't want to refresh the entire row but only the view of the row. (to avoid the blinking effect of the row)

There is a method called notifyItemChanged(int, payload obj).

Can I use that to achieve that? If so how to do it?


Solution

  • Finally I found how to update only the specific view of a row in RecyclerView.

    (1) Override onBindViewHolder(Recycler.ViewHolder VH, int position, List payloads) in the adapter

    (2) Inside that onBindViewHolder method,

    if(payloads != null && !payloads.isEmpty() && (payloads.get(0) instanceof  customObject)){
       // update the specific view
    }else{
       // I have already overridden  the other onBindViewHolder(ViewHolder, int)
       // The method with 3 arguments is being called before the method with 2 args. 
       // so calling super will call that method with 2 arguments. 
       super.onBindViewHolder(holder,position,payloads);
    }
    

    (3) So to notify data change and update the view, need to call the notifyItemChanged(int position, Object payload). Need to pass the customObject(model which holds the data) as the payload object.

    adapter.notifyItemChanged(i, obj);
    

    Note : Need to disable the RecyclerView's ItemAnimator(By default it is enabled). Otherwise payload object will be empty.

    recyclerView.setItemAnimator(null);
    

    or

    ((SimpleItemAnimator)recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
    

    UPDATE: I used this method recently without disabling the ItemAnimator. So no need to disable ItemAnimator. - (recyclerview-v7:25.4.0)

    for further reference