繁体   English   中英

在 Kotlin 中同时处理按钮单击和按钮触摸

[英]Handling button click and button touch simultaneously in Kotlin

这是一些看似经典的代码,我在一个小型 android 应用程序中。 它正在处理一些按钮,所以没什么特别的; 但这是一个问题:

只要我选择使用theBtn.setOnClickListener {..}theBtn.setOnTouchListener {..}这两个功能块之一,此代码就可以工作。

但如果我想同时拥有两者,它就不再起作用了。 我错过了什么吗?

    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)

因为onTouch和onClick会冲突,当你消费onTouchListener中的事件时,即return@setOnTouchListener true; 不会再次执行点击,如果想让点击事件在ACTION_UP之后执行,只需return@setOnTouchListener false

就像 Selvin 说的,如果你只是想改变按钮按下时的颜色或背景,你不应该这样做,使用可绘制选择器是最好的!

您似乎为两个不同的听众重用了同一个按钮。 我不是太有经验,但是你如何让它同时做两个不同的动作? 也许使用 when 语句进行运动,然后调用触摸侦听器,否则使用 onClick? 对不起,如果这不起作用。 请让我知道! 也很好奇:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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