4

I have a RecyclerView with rows that have views that when clicked will be disabled for that row position.

The problem is after I update the adapter like this:

    adapterData.clear();
    adapterData.addAll(refreshedAdapterData);
    notifyDataSetChanged();

After refreshing the data, the disabled views at the previous recycler position still remain disabled even though the data is refreshed. How can I reset the views to the original state after refreshing adapter data.

CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
S bruce
  • 1,514
  • 3
  • 16
  • 24

4 Answers4

6

Use below code.

  adapterData.clear();
adapterData.addAll(refreshedAdapterData);

adapter.notifyDataSetChanged();

OR

recyclerView.invalidate();
valerybodak
  • 4,195
  • 2
  • 42
  • 53
Keyur Thumar
  • 608
  • 7
  • 19
2

When you call notifyDataSetChanged(), the onBindViewHolder() method of every view is called. So you could add something like this in the onBindViewHolder() of your Adapter method:

@Override   
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
            if (refreshedAdapterData.get(position).isInDefaultState()) {
                //set Default View Values
            } else {
                //the code you already have
            }

        }
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Christoph Mayr
  • 347
  • 3
  • 17
1

I have resolved this by putting a conditional statement inside onBindViewHolder method instructing all positions to reset the disabled views if data meets the required conditions for a refreshed data.

@Christoph Mayr, thanks for your comments. It helped point me in the right direction.

S bruce
  • 1,514
  • 3
  • 16
  • 24
0

I cleared the data then notify change but the selected checkbox doesn't reset but just moves up one position. Let say I selected item #1 , move out of the RecyclerView, came back and it will auto select item #0.

So, I created new adapter again at onResume(), i worked for me but i don't know if it's the right way to handle this situation.

    @Override
    public void onResume() {
        super.onResume();
        if(selectedItems != null && selectedItems.size() > 0){
            selectedItems.clear(); // if no selected items before then no need to reset anything
            if(adapter != null && recyclerView != null){
                // to remove the checked box
                adapter = null;
                adapter = new MyAdapter(items, new MyAdapter.MyAdapterListener() {
                    @Override
                    public void onSelected(int pos) {
                        selectedItems.add(items.get(pos));
                    }

                    @Override
                    public void onUnSelected(int pos) {
                        selectedItems.remove(items.get(pos));
                    }
                });
                recyclerView.setAdapter(adapter);

            }

        }
    }