can't use a toast message in the recyclerview


I am making recyclerview in kotlin in android studio. I’m trying to set up an event listener that puts a button in the recyclerview and outputs a toast message. Even if [email protected][activity name] is entered instead of this in context, a toast message is not displayed. What went wrong?

The error code is as follows.

Unresolved reference: @UpdateActivity

class UpdateActivity : AppCompatActivity() {

    private val vBinding by lazy {ActivityUpdateBinding.inflate(layoutInflater)}

    override fun onCreate(savedInstanceState: Bundle?) {
        var recyclerViewAdapter = CustomAdapter()
        recyclerViewAdapter.listData = arrayListOf<String>("a", "b", "c")
        vBinding.uploadedRecyclerView.adapter = recyclerViewAdapter
        vBinding.uploadedRecyclerView.layoutManager = LinearLayoutManager(this)
    } // onCreate End

    class CustomAdapter:RecyclerView.Adapter<CustomAdapter.Holder>(){
        var listData = arrayListOf<String>()
        class Holder(val vBinding:UploadedRecyclerBinding):RecyclerView.ViewHolder(vBinding.root){
            fun setData(name:String){
       = name
                vBinding.getBtn.setOnClickListener {
                    **Toast.makeText([email protected], "test", Toast.LENGTH_SHORT).show()**
                                       // ↑A compilation error occurs here.**
        } // Holder end
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
            val vBinding = UploadedRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            return Holder(vBinding)
        override fun onBindViewHolder(holder: Holder, position: Int) {
            val name = listData[position]
        override fun getItemCount(): Int {
            return listData.size
    } // CustomAdapter end

} // UpdateActivity end


you could try put context into constructor of adapter when you create it, and use this context to show a toast. something like this:

class CustomAdapter(
    private val mContext: Context

and in holder class:

Toast.makeText(mContext, "test", Toast.LENGTH_SHORT).show()

finally, when you create adapter in activity:

var recyclerViewAdapter = CustomAdapter(this)

Normally, we’ll create adapter class in another file, so use [email protected] in adapter is bad idea

Answered By – ninhnau19

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published