Im working on an app which has a RecyclerView inside a Fragment. My objective, is to set up onClickItemListener trough the adapter.
However, i encountered a problem setting it up: when i call the adapter, i have to put two parameters, which are the list that i need to apply, and the listener.
If i put this
as listener, i get a TypeMismatch error.
What can i use instead of this
?
Fragment.kt
class FragmentItems : Fragment() {
var itemList = mutableListOf<DataItems>()
....
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
....
rvTracks.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(activity)
//Cant use 'this'!
adapter = AdapterList(itemList, this)
}
}
}
Adapter.kt
class AdapterList(
var listItems: List<DataItems>,
var listener: OnItemClickListener
) : RecyclerView.Adapter<AdapterOneColumn.ItemsViewHolder>() {
inner class ItemsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
init {
itemView.setOnClickListener(this)
}
override fun onClick(p0: View?) {
val position : Int = adapterPosition
if(position != RecyclerView.NO_POSITION) {
listener.OnItemClick(position)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemsViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_1_column, parent, false)
return ItemsViewHolder(view)
}
override fun getItemCount(): Int {
return listItems.size
}
override fun onBindViewHolder(holder: ItemsViewHolder, position: Int) {
holder.itemView.apply {
itemOneColumnTitle.text = listItems[position].stringTitle
itemOneColumnDescription.text = listItems[position].stringDescription
}
}
interface OnItemClickListener {
fun OnItemClick(position: Int)
}
}
if you want to make this work
adapter = AdapterList(itemList, this)
Your class should realize OnItemClickListener
that you want to pass, you can fix it by :
class FragmentItems : Fragment(), OnItemClickListener { ...
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.