Issue
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!
Solution
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, e.g.
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, e.g.
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int)
{
val itemHolder = holder as ItemViewHolder
val item = dataModel[position]
itemHolder.mFieldView.text = item.field
}
Answered By - Chris Shaw
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.