How to create onclick event in adapter using interface android?

前端 未结 3 1433
一生所求
一生所求 2021-01-03 08:05

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

3条回答
  •  甜味超标
    2021-01-03 08:27

    In Kotlin the proper way doing this, is using callbacks instead of Java Interfaces. Example:

    class MyAdapter(private val callback: (YourModel) -> Unit) {
    
        override fun onBindViewHolder(holder: DataBoundViewHolder, position: Int) {
            bind(holder.binding, items!![position])
            holder.binding.executePendingBindings()
            holder.binding.root.setOnClickListener { callback(binding.model) }
       }
    }
    

    And create the adapter somewhere using

    MyAdapter myAdapter = MyAdapter( { println{"Clicked $it"} })
    

    Edit: Since the Asker would like to see a full working code i used the code from Sumit and replaced the Interfaces with Kotlin-Callbacks.

    class ChapterAdapter(private val activity: Activity, 
         val mWords: ArrayList,
         val callback: (Any) -> Unit) : 
         RecyclerView.Adapter() {
    
    
            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) {
                val item = mWords[position]
    
                holder.layout_chapter_name.setOnClickListener( callback {$it})
            }
    
            override fun getItemCount(): Int = mWords.size
    
            override fun getItemId(position: Int): Long = super.getItemId(position)
    
            override fun getItemViewType(position: Int): Int = super.getItemViewType(position)
    
    
            class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
                val txt_capter_name = view.txt_capter_name
            }
    

    and finally creating the Adapter

    listAdapter = ChapterAdapter(activity, _arrChapterList, { 
      toast( "Clicked $it", Toast.LENGTH_LONG) 
    })
    

提交回复
热议问题