What difference between static and non static viewholder in RecyclerView Adapter?

Lester picture Lester · Jul 8, 2015 · Viewed 15k times · Source

What are the advantages of this approach (using static nested class in my class MyAdapter extends RecyclerView.Adapter):

static class MyVH extends RecyclerView.ViewHolder {...}

And this approach (using member inner class):

  class MyVH extends RecyclerView.ViewHolder {...}

Or it doesn't affect performance and both approaches could be used?

Answer

droidpl picture droidpl · Jul 8, 2015

It is more a java question than an Android question. It is recommended to use static for inner classes to avoid memory leaks if you will take their instances out of the class. You can have a look at this awesome post that explains the memory leaks on inner classes.

Basically what nyx says:

  • If you declare the viewholder as static you can reuse it in other adapters. Anyway, I do not recommend to do it, create a new separated class and use it from multiple places, it does make more sense. One class for one purpose.
  • In the case of view holders, this classes will be only used inside the adapter, their instances should not go to the fragment or activity or elsewhere just by definition. This means having it static or non-static, in the case of view holders, is the same.

Answering your performance question, you can have a look at this answer. The static one will take less memory than the other one, but again, we are talking about recyclers which will recycle the instances, so the memory impact is not a problem.