11

I want to create a code to click on items of RecyclerView. I found one from Internet, however it keep getting this error:

None of the following functions can be called with the arguments supplied:

public open fun makeText(p0: Context!, p1: CharSequence!, p2: Int): Toast! defined in android.widget.Toast

public open fun makeText(p0: Context!, p1: Int, p2: Int): Toast! defined in android.widget.Toast

Here's my code:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        val users = ArrayList<User>()

        val adapter = CustomAdapter(users)

        recyclerView.adapter = adapter

        recyclerView.addOnItemClickListener(object : OnItemClickListener {
            override fun onItemClicked(position: Int, view: View) {
                Toast.makeText(this, "Clicked on  " + users.get(position).name, Toast.LENGTH_LONG).show()
            }
        })


    }

    interface OnItemClickListener {
        fun onItemClicked(position: Int, view: View)
    }

    fun RecyclerView.addOnItemClickListener(onClickListener: OnItemClickListener) {
        this.addOnChildAttachStateChangeListener(object : RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewDetachedFromWindow(view: View) {
                view.setOnClickListener(null)
            }

            override fun onChildViewAttachedToWindow(view: View) {
                view.setOnClickListener {
                    val holder = getChildViewHolder(view)
                    onClickListener.onItemClicked(holder.adapterPosition, view)
                }
            }
        })
    }

How can I fix that error message?

Community
  • 1
  • 1
FY Gamer
  • 197
  • 1
  • 1
  • 9

2 Answers2

11
Toast.makeText(this@YOUR_ACTIVITY_NAME, "Clicked on  " + users.get(position).name, Toast.LENGTH_LONG).show()
Amir Abbas
  • 305
  • 3
  • 8
  • That worked, thanks! Could you explain me why? I have seen Toast working with only 'this'. – FY Gamer Oct 09 '19 at 16:19
  • when you are setting addOnItemClickListener in input you are passing an instance of an abstract class so when you call "this" you are referring to inner class instance ( object : OnItemClickListener ) then you have to say that "this" refer to activity class not OnItemClickListener. – Amir Abbas Oct 09 '19 at 18:25
  • Got it. Thank you a lot. – FY Gamer Oct 09 '19 at 19:09
6
//In Activity use: 
Toast.makeText(this@YOUR_ACTIVITY_NAME, "your message", Toast.LENGTH_LONG).show()
    
//In Fragments use: 
Toast.makeText(requireActivity(), "your message", Toast.LENGTH_LONG).show()
 
Your problem will be solved...
Dharmik Thakkar
  • 1,650
  • 1
  • 9
  • 18