How to get clicks on RecyclerView (NOT the children)

前端 未结 4 1159
我在风中等你
我在风中等你 2021-01-17 17:23

Is there any way to set an onClickListener on a RecyclerView?

I have a RecyclerView with some children in it, and setting an <

4条回答
  •  不知归路
    2021-01-17 17:55

    This is how I have done in Kotlin style

    fun RecyclerView.enableClickListener(){
        val gesture = object : GestureDetector.SimpleOnGestureListener(){
            override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
                this@enableClickListener.performClick()
                return super.onSingleTapConfirmed(e)
            }
        }
        val detector = GestureDetector(this.context, gesture)
        this.setOnTouchListener { v, event -> detector.onTouchEvent(event) }
    }
    

    And this is how to use it

    yourRecyclerView.apply {
            enableClickListener()
            setOnClickListener {
               // Do what you want  ...
            }
        }
    

    Enjoy :)

提交回复
热议问题