简体   繁体   中英

Kotlin: Type mismatch (RecyclerView.Adapter<RecyclerView.ViewHolder>)

I'm pretty new using Kotlin, I tried to port my project from java to kotlin. Basically, I have a helper class that try to init recyclerview layout, adapter and so on.

In java: Adapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
  ...
  public static class ViewHolder extends RecyclerView.ViewHolder
  {
    ...
  }
  ...
}

my helper function:

public void init(RecyclerView recyclerView, boolean horizontal, boolean divider, RecyclerView.Adapter adapter, Context context)

When I created the adapter and call the function, it works fine.

But in Kotlin: Adapter

class MyAdapter(...) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
  ...
  inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    ...
  }
  ...
}

helper function

fun init(recyclerView : RecyclerView, horizontal: Boolean, divider: Boolean, adapter: RecyclerView.Adapter<RecyclerView.ViewHolder>, context: Context) {
  ...
}

when I created the adapter and call the function

val myAdapter = MyAdapter(...)
helper.init(listView, false, false, myAdapter, this)

I got mismatch error where it required: RecyclerView.Adapter<RecyclerView.ViewHolder> and found: MyAdapter

Inheritance wise, it should work right? or did I miss something?

Thanks!

Not quite, the correct declaration you require is:

class MyAdapter() : RecyclerView.Adapter<RecyclerView.ViewHolder>() 

and you then need to implement methods such as this signature:

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder

etc.

onCreateViewHolder must return a ViewHolder or a subclass of it, eg

return ItemViewHolder(view)

where:-

inner class ItemViewHolder(val mView: View) : RecyclerView.ViewHolder(mView)
{
  val mFieldView: TextView = mView.field
  ...
}

and you can use this knowledge within the bind function, eg

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int)
{
  val itemHolder = holder as ItemViewHolder
  val item = dataModel[position]
  itemHolder.mFieldView.text = item.field
}

Check out the type of adapter you are using, there are different types of adapter like array adapter, recyclerView Adapter. Specifically, in list views, we use an array adapter. While with recycler View adapter used is recycler view adapter and it will show the above error if you use array adapter with recycler view.

I had the same issue. Replace RecyclerView.Adapter<RecyclerView.ViewHolder> with RecyclerView.Adapter<*>

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