如何修改代码实现左右按钮同时按下时输出对应日志?
Hey there! Let's figure out why your code isn't detecting both buttons being pressed at the same time. The core issue here is that your pressed() function only receives one button's state at a time (the other parameter is null), so the check left == true && right == true will never trigger—since one value is always null when you call it.
The Solution: Track Persistent Button States
We need to maintain two class-level variables to keep track of each button's pressed state, then update these variables whenever a touch event occurs. After each update, we check if both buttons are pressed and log the appropriate message.
Here's the corrected code:
// Add these class-level variables to track each button's state private var isLeftPressed = false private var isRightPressed = false // Updated touch listener val handleTouch = View.OnTouchListener { v, event -> when(v) { btn_leftThumb -> { isLeftPressed = when(event.action) { MotionEvent.ACTION_DOWN -> true MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> false else -> isLeftPressed // Keep state for other events like ACTION_MOVE } } btn_rightThumb -> { isRightPressed = when(event.action) { MotionEvent.ACTION_DOWN -> true MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> false else -> isRightPressed // Keep state for other events like ACTION_MOVE } } } // Check and log the current button state combination when { isLeftPressed && isRightPressed -> Log.i(TAG, "BOTH") isRightPressed -> Log.i(TAG, "RIGHT") isLeftPressed -> Log.i(TAG, "LEFT") else -> Log.i(TAG, "NONE") // Optional: log when both are released } true } // Attach the listener to both buttons btn_leftThumb.setOnTouchListener(handleTouch) btn_rightThumb.setOnTouchListener(handleTouch)
Key Changes Explained:
- Persistent State Variables:
isLeftPressedandisRightPressedlive at the class level, so they retain their values between touch events instead of being passed as one-off null parameters. - Complete Touch Event Handling: We handle
ACTION_CANCEL(along withACTION_UP) to reset the state if the touch is interrupted (e.g., the user swipes off the button instead of lifting their finger). We also preserve the state forACTION_MOVEevents, since the button is still pressed during those. - Post-Update State Check: After updating either button's state, we immediately check the combination of both states. This ensures the "BOTH" log triggers as soon as the second button is pressed.
This approach will correctly detect when both buttons are pressed simultaneously and log the expected message.
内容的提问来源于stack exchange,提问作者jeiboi

