Search code examples
androidandroid-recyclerviewcustom-adapterandroid-viewholder

Update ViewHolder values of custom Adapter for Recyclerview


I have a RecyclerView with a custom Adapter to display rectangular elements (about 15, the number can change if the user adds/removes items) in a grid (using Gridlayout Manager). RecyclerView

These elements consist of an ImageView and a TextView. I want to update both Views regularly after receiving new results from network requests (say every 2minutes).

What would be the best way to update these views? How can I identify the specific ViewHolder? How can I access the ViewHolder values of these elements? Would it be best to keep a reference to each ViewHolder in the Activity where I want to change them? Or should I create a new element with the new values and replace the current element with it? What would be considered best practice?


Solution

  • If you are storing your value of image view and text view in an arraylist you can call notifyDataSetChanged on the adapter when you have a change in the dataset.

    For example if you have say a Grid object whose attributes include image uri(to set the image) and string(to set in text view) and some Array list say

    List<Grid> gridList = new ArrayList<>();
    

    you can update whatever new data you get in the Arraylist and after you are done updating in the array list call

    adapter.notifyDataSetChanged();