简体   繁体   中英

what is the difference between extends Recyclerview.Adapter vs RecyclerView.Adapter<SubclassRecyclerViewAdapter.ViewHolder> in RecyclerView

I have been reading online about RecyclerView in Android. As a beginner, I have seen some online tutorials extend RecyclerView.Adapter<Subclass_RecyclerviewAdapter.ViewHolder> and some RecylerView.Adapter only. Actually, what is the difference between them? which is better?

If I do this:

class SimpleAdapter : RecyclerView.Adapter() { ... }

then Android Studio says "One type argument expected for class Adapther<VH: RecyclerView.ViewHolder!> ". In the source for the RecyclerView , you can see:

public class RecyclerView extends ViewGroup implements ScrollingView,
        NestedScrollingChild2, NestedScrollingChild3 {

    ...

    public abstract static class Adapter<VH extends ViewHolder> { ... }

    ... 

}

That means you have to supply a type to the Adapter constructor (similar to how you don't define a List , but a List<String> for example).

There is a thing to note here, though. You can put RecyclerView.ViewHolder as the type, or you can extend this class and use your custom ViewHolder . This allows you to define custom methods on the ViewHolder , for example:

inner class SimpleViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
    fun bind(text: String) {
        // Bind to the view
    }
}

EDIT: Important thing is, you receive the type you use in the constructor in the adapter methods, for example: override fun onBindViewHolder(holder: SimpleViewHolder, position: Int) {... } , where you can then use your methods from the custom view holder.

And, you will have to have a custom VH, as the RecyclerView.ViewHolder is abstract .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM