Search code examples
androidkotlinontouchlistener

Kotlin OnTouchListener called but it does not override performClick


How to override performClick in Kotlin to avoid warning?

next.setOnTouchListener(View.OnTouchListener { view, motionEvent ->
        when (motionEvent.action){
            MotionEvent.ACTION_DOWN -> {
                val icon: Drawable = ContextCompat.getDrawable(activity.applicationContext, R.drawable.layer_bt_next)
                icon.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
                next.setImageDrawable(icon)
            }
            MotionEvent.ACTION_UP -> {
                //view.performClick()
                next.setImageResource(R.drawable.layer_bt_next)
            }
        }
        return@OnTouchListener true
    })

view.performClick does not work.


Solution

  • Okay, I solved my own problem by overriding the OnTouch listener.

    override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
        when (view) {
            next -> {
                Log.d("next", "yeyy")
                when (motionEvent.action){
                    MotionEvent.ACTION_DOWN -> {
                        val icon: Drawable = ContextCompat.getDrawable(activity.applicationContext, R.drawable.layer_bt_next)
                        icon.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
                        next.setImageDrawable(icon)
                    }
                    MotionEvent.ACTION_UP -> {
                        view.performClick()
                        next.setImageResource(R.drawable.layer_bt_next)
                    }
                }
            }
            previous -> {
                //ingredients here XD
            }
        }
        return true
    }
    

    And in that way, I can call single onTouch and implement it to many button and also can use the onClick by :

    view.performClick()
    

    Don't forget to implement :

    View.OnTouchListener
    

    And set the listener :

    next.setOnTouchListener(this)
    previous.setOnTouchListener(this)