Search code examples
androidkotlinbuttononclicklistenerontouchlistener

Handling button click and button touch simultaneously in Kotlin


Here is some seemingly classical code, that I have in a small android app. It is handling some button, so nothing special going on; but this is the question:

This code work as long as I choose to have one of the two function blocks theBtn.setOnClickListener {..} or theBtn.setOnTouchListener {..}.

But it no longer works if I want to have both at the same time. Am I missing some thing ?

    val greyLvl = 0x89
    val stdColor = Color.rgb(greyLvl,greyLvl,greyLvl)
    val hiLiColor = Color.rgb(0x33,0x66,0x88)

    val theBtn = Button(this)
    theBtn.setTextColor(stdColor)
    theBtn.setBackgroundColor(0x00)
    theBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, 31.dpToPixels(this))
    theBtn.setTypeface(null, Typeface.BOLD)
    theBtn.text = "THE BUTTON"


    theBtn.setOnClickListener {
        // Handling the button action.
        println("-- theBtn.setOnClickListener --")
    }


    theBtn.setOnTouchListener { view, motionEvent ->
        // Controlling the button color.
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            theBtn.setTextColor(hiLiColor)
        } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
            theBtn.setTextColor(stdColor)
        }

        return@setOnTouchListener true;
    }


    scrolVwLayOut.addView(theBtn)

Solution

  • Because onTouch and onClick will conflict,When you consume the event in onTouchListener, that is return@setOnTouchListener true; will not execute the click again, if you want the click event to be executed after ACTION_UP, just return@setOnTouchListener false

    Like Selvin said, if you just want to change the color or background of the button when pressed, you shouldn't do it this way,use drawable selector is the best!