-1

I want to implement alertdialog in my adapter for my recyclerview in my fragment. but there is an error about context, how to set context in adapter?

 override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

        val currentitem = obatList[position]

        holder.namaObat.text = currentitem.namaObat
        holder.harga.text = currentitem.harga
        holder.keterangan.text = currentitem.keterangan
        holder.edit.setOnClickListener {
           showUpdateDialog()
        }

    }

    private fun showUpdateDialog() {
        val builder = AlertDialog.Builder()
    }
    
        override fun getItemCount(): Int {
    
            return obatList.size
        }
    
    
        class MyViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){
    
            val namaObat : TextView = itemView.findViewById(R.id.tvNamaObat)
            val harga : TextView = itemView.findViewById(R.id.tvHarga)
            val keterangan : TextView = itemView.findViewById(R.id.tvKeterangan)
            val edit : ImageButton = itemView.findViewById(R.id.ibEdit)
        }
    }
Octa Dion
  • 5
  • 1

2 Answers2

0

All you have to do is get the "context" as a class creator.

Fragment.kt

YourAdapter(requireContext())

YourAdapter.kt

YourAdapter(context: Context){

    showUpdateDialog(){
        AlertDialog.Builder(context) 
    }

}
Shin Dong Hwi
  • 71
  • 1
  • 3
0

First make your function take a context parameter that you can pass to your builder:

private fun showUpdateDialog(context: Context) {
    val builder = AlertDialog.Builder(context)
        //...
}

Then you can get a context to pass from your binding root or the view passed to your click listener:

    holder.edit.setOnClickListener { view ->
       showUpdateDialog(view.context)
    }

or

    holder.edit.setOnClickListener {
       showUpdateDialog(it.context)
    }
Tenfour04
  • 83,111
  • 11
  • 94
  • 154