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?
A ViewHolder describes an item view and metadata about its place within the RecyclerView. RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive View.
ViewHolder: ViewHolder is a type of helper class that allows us to draw the UI for individual items on the screen. LayoutManager: LayoutManager in recyclerView assists us in determining how to display the items on the screen. It can be done either linearly or in a grid.
onCreateViewHolder(parent: ViewGroup, viewType: Int) Parent is the ViewGroup into which the new View will be added after it is bound to an adapter position and viewType is the type of the new View. This method will return a new ViewHolder that holds a View of the given view type.
onCreateViewHolder only creates a new view holder when there are no existing view holders which the RecyclerView can reuse. So, for instance, if your RecyclerView can display 5 items at a time, it will create 5-6 ViewHolders , and then automatically reuse them, each time calling onBindViewHolder .
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:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With