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

纵然是瞬间 提交于 2019-11-28 03:05:47
droidpl

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.

By using static it just means you can re-use MyVh in other adapters. If you know for certain that you'll only need MyVh in that one adapter, then you should make it non-static.

If you will need it in other adapters it may even be better to just create it as a separate class entirely, rather than a nested class.

There should be no effects on performance for static vs non-static!

Prashant Kumar

If you want to use one viewholder in many places then it is recommended to create separate classes. Otherwise, if you want to use viewholder only in one place, then create a non-static nested viewholder. A static viewholder doesn't make any sense

In most places, I use nested viewholder class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!