這是一些看似經典的代碼,我在一個小型 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)
uj5u.com熱心網友回復:
因為onTouch和onClick會發生沖突,當你消費onTouchListener中的事件時,即 return@setOnTouchListener true;不會再次執行點擊,如果你想讓點擊事件在之后執行ACTION_UP,只需return@setOnTouchListener false
就像 Selvin 說的,如果你只是想改變按鈕按下時的顏色或背景,你不應該這樣做,使用可繪制選擇器是最好的!
uj5u.com熱心網友回復:
您似乎為兩個不同的聽眾重用了同一個按鈕。我不是太有經驗,但是你如何讓它同時做兩個不同的動作?也許使用 when 陳述句進行運動,然后呼叫觸摸偵聽器,否則使用 onClick?對不起,如果這不起作用。請讓我知道!也很好奇:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487478.html
上一篇:“跳轉到訊息”按鈕
下一篇:具有動態變數的ForEach回圈
