Home > other >  can't use a toast message in the recyclerview
can't use a toast message in the recyclerview

Time:10-12

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 this@[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?) {
        super.onCreate(savedInstanceState)
        setContentView(vBinding.root)
        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){
                vBinding.name.text = name
                vBinding.getBtn.setOnClickListener {
                    **Toast.makeText(this@UpdateActivity, "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]
            holder.setData(name)
        }
        override fun getItemCount(): Int {
            return listData.size
        }
    } // CustomAdapter end

} // UpdateActivity end

CodePudding user response:

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
):RecyclerView.Adapter<CustomAdapter.Holder>(){

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 this@UpdateActivity in adapter is bad idea

CodePudding user response:

Instead of using the local context in Toast, always use applicationContext when showing it. So, you should replace that creation of Toast message as,

Toast.makeText(applicationContext, "test", Toast.LENGTH_SHORT).show()
  • Related