How can I create on click event using interface?
In my application I've created view click interface to detect clicking on adapter items into parent activity. After creating interface and method into adapter how I can use this interface to call the view listener ?
Where do you add the android:onClick attribute to make items in a RecyclerView respond to clicks? In the layout file that displays the RecyclerView, add it to the element. Add it to the layout file for an item in the row.
When the user clicks a button, the Button object receives an on-click event. To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.
Update the ViewHolder to take in onClick() as a parameter. In the initializer, call setOnClickListener{} on the itemView . That's it! Your RecyclerView is now responsive so time to get your click on!
Please check this code, It's working fine for me.
First Create Adapter class.
class ChapterAdapter(private val activity: Activity, val mWords: ArrayList<Chapter>, val btnlistener: BtnClickListener) : RecyclerView.Adapter<ChapterAdapter.ViewHolder>() {
companion object {
var mClickListener: BtnClickListener? = null
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return ViewHolder(layoutInflater.inflate(R.layout.layout_capter_raw, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
mClickListener = btnlistener
val item = mWords[position]
holder.layout_chapter_name.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
if (mClickListener != null)
mClickListener?.onBtnClick(position)
}
})
}
override fun getItemCount(): Int {
return mWords.size
}
override fun getItemId(position: Int): Long {
return super.getItemId(position)
}
override fun getItemViewType(position: Int): Int {
return super.getItemViewType(position)
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val txt_capter_name = view.txt_capter_name
}
open interface BtnClickListener {
fun onBtnClick(position: Int)
}
}
After create and declare adapter in your Activity or Fragment.
listAdapter = ChapterAdapter(activity, _arrChapterList, object : ChapterAdapter.BtnClickListener {
override fun onBtnClick(position: Int, chapter_id: String, chapter_size: String, chapter_name: String) {
toast(chapter_id + " = " + chapter_size, Toast.LENGTH_LONG)
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With