简体   繁体   中英

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)

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!

It seems you reused the same button for two different listeners. I am not too experienced, but how would you get it to do two different actions at the same time? maybe use a when statement for motion and then call the touch listener, else use onClick? Sorry if that doesn't work. Let me know though please! Also curious :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM