I know the title is a bit weird, sorry. This is a weird one that I'm not even sure I can explain it correctly, here is my attempt:
Basically I want to implement a wrapper for any adapters that extend RecyclerView.Adapter<RecyclerView.ViewHolder>
, the wrapper eventually will be able to insert rows if needed and it will modify things like getItemCount()
as necessary, but I'm nowhere near that part yet.
This is my class definition:
class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
I pass to it the original adapter which I want to wrap.
If I have the class definition like that, and then I try to create an instance of MyRecyclerAdapterWrapper
like this:
val wrapper = MyRecyclerAdapterWrapper(activity, myOriginalAdapter)
Where myOriginalAdapter
is an instance of:
class MyOriginalAdapter() : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {
I then get an error saying that it is expecting RecyclerView.Adapter<RecyclerView.ViewHolder>
but instead got MyOriginalAdapter
.
So then I tried the out
keyword on the class definition like this:
class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
And that allows my constructor call MyRecyclerAdapterWrapper(activity, myOriginalAdapter)
to stop complaining, however then my MyRecyclerAdapterWrapper
class fails at implementing some of the RecyclerView.Adapter<RecyclerView.ViewHolder>
overrides because originalAdapter
expects Nothing
instead of RecyclerView.ViewHolder
.
For example inside MyRecyclerAdapterWrapper
I have this piece of code:
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
originalAdapter.onBindViewHolder(holder,position)
}
The error here is Type mismatch
Required: Nothing
Found: RecyclerView.ViewHolder
.
So what is the correct way to handle this?
Edit: just wanted to be clear that other adapters will also use this wrapper, so the wrapper must be generic.
parameter require Nothing
because you declared out
for generic parameter
try to change RecyclerView.ViewHolder
to MyOriginalAdapter.MyViewHolder
class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>) : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyOriginalAdapter.MyViewHolder {
TODO("Not yet implemented")
}
override fun onBindViewHolder(holder: MyOriginalAdapter.MyViewHolder, position: Int) {
originalAdapter.onBindViewHolder(holder, position)
}
override fun getItemCount(): Int {
TODO("Not yet implemented")
}
}
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.