1

I have a function that shrinks the size of a view on ACTION_DOWN, and returns it to original size on ACTION_UP. This function is strictly for aesthetics. I have setOnClickListeners on the buttons so they can (in theory...) execute code when the button is pressed.

private fun scaleButton(theButton:View, grow:Boolean){
    theButton.setOnTouchListener(View.OnTouchListener { v, event ->
        if (event.action == MotionEvent.ACTION_DOWN) {
            v.isPressed = true

            if (grow) {
                v.animate().scaleX(1.04F).scaleY(1.04F).setDuration(50)
            } else {
                v.animate().scaleX(0.97F).scaleY(0.97F).setDuration(50)
            }

        } else if (event.action == MotionEvent.ACTION_UP) {
            v.isPressed = false
            v.animate().scaleX(1.0F).scaleY(1.0F).setDuration(100)
        }
        false
    })
}

The problem is setOnClickListener is never called.

onCreate:

scaleButton(button1,false)
scaleButton(button2,true)
scaleButton(button3,false)

button1.setOnClickListener {
    println("Button 1 Pressed")
}
button2.setOnClickListener {
    println("Button 2 Pressed")
}
button3.setOnClickListener {
    println("Button 3 Pressed")
}

How can I both scale the button via animation (on touch) AND trigger setOnClickListener

Joe
  • 3,772
  • 3
  • 33
  • 64
  • did you try to return 'false' in 'OnTouchListener'? – Vigen May 22 '19 at 21:53
  • Yes. That didn't change anything. I edited the code in my original post. – Joe May 22 '19 at 22:07
  • Ok I googled a little bit. May be this one will help https://stackoverflow.com/questions/19538747/how-to-use-both-ontouch-and-onclick-for-an-imagebutton? – Vigen May 22 '19 at 22:14

1 Answers1

3

Your click listener will never fire because the touch listener is supposed to tell the system when the elemnt was clicked. Yours isn't. Either add a performClick at the appropriate time, or put everything into the touch listener and perform the click on action_up

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Thanks Gabe. Adding performClick() at the end of ACTION_UP did the trick. – Joe May 22 '19 at 22:38
  • 1
    That's the better solution anyway. I just remembered the other reason to do that- without it accessibility features won't work on that view – Gabe Sechan May 22 '19 at 22:41