Hoang Ha
Hoang Ha

Reputation: 1075

How can I override methods notifyDataSetChanged, notifyItemChanged ... of RecyclerView Adapter

As the title. I'm writing a custom RecyclerView which supports multi select mode. And I need tracking selected/unselected state of each item. So after data size of recyclerView has changed. I want to update size of my tracking state list. But I don't know where to override methods : notifyDataSetChanged, notifyItemChagned ....

Upvotes: 6

Views: 7563

Answers (4)

George Arokiam
George Arokiam

Reputation: 262

Register the adapter as the RecyclerView.Adapter's observer.

yourRecyclerView.getAdapter().registerAdapterDataObserver(new AdapterDataObserver() {
    @Override
    public void onChanged() {
        // Do nothing
    }
});

Upvotes: 5

mikepenz
mikepenz

Reputation: 12858

As the previous answer already correctly stated. You can't as those methods are final.

I came into the same situation when implementing the FastAdapter

The only solution I came up with is to name those methods slightly different. notifyDataSetChanged -> notifyAdapterDataSetChanged https://github.com/mikepenz/FastAdapter/blob/develop/library/src/main/java/com/mikepenz/fastadapter/FastAdapter.java#L1354

public void notifyAdapterDataSetChanged() {
    //... your custom logic
    notifyDataSetChanged();
}

For the library it was quite important to improve the documentation regarding this point, but it is the only solution as of now.

Upvotes: 20

Ankit Singh
Ankit Singh

Reputation: 31

You can't because you can't override final methods.

Upvotes: 0

Kishore Jethava
Kishore Jethava

Reputation: 6834

You can't because it's final in RecyclerView.Adapter see here

You can override using BaseAdapter with ListView

@Override
public void notifyDataSetChanged() {
    // TODO Auto-generated method stub
    super.notifyDataSetChanged();
}

Upvotes: 8

Related Questions