0

I want to prevent a button from intercepting 2 finger taps. I have a standard Android Activity with onTouchEvent and a standard button which occupies more or less the entire screen.

private const val DEBUG_TAG = "Gestures"
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val button = this.findViewById<Button>(R.id.button2)
        button.setOnClickListener { Log.d(DEBUG_TAG, "Button tapped")
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        Log.d(DEBUG_TAG, "onTouchEvent")
        val action: Int = MotionEventCompat.getActionMasked(event)
        val pointerCount = event.pointerCount;
        if (pointerCount > 1) {
          Log.d(DEBUG_TAG, "Multi-touch")
        }
        return super.onTouchEvent(event)
    }
}

I want the button to intercept 1 finger taps but ignore 2 finger taps and propagate them to the onTouchEvent of the activity. Currently it intercepts even 2 finger taps.

I tried this in styles.xml but no luck.

 <item name="android:windowEnableSplitTouch">false</item>
 <item name="android:splitMotionEvents">false</item>

Ideally I would like to do that app-wide but still having onTouchEvent being able to detect 2 finger taps.

Foti Dim
  • 1,303
  • 13
  • 19

1 Answers1

0

You need to block events you don't want to propagate:

override fun onTouchEvent(event: MotionEvent): Boolean {
  val action: Int = MotionEventCompat.getActionMasked(event)
  val pointerCount = event.pointerCount;
  return when (pointerCount) {
    1 -> {
      // your logic
      true //true means you consumed the event (stop propagation)
    }
    else -> super.onTouchEvent(event)
  }
}
MatPag
  • 41,742
  • 14
  • 105
  • 114
  • But when I tap on the button `onTouchEvent` is not even called. – Foti Dim Jul 07 '20 at 16:15
  • This is another problem. Maybe there is another onTouchEvent which consumes the event before you have a chance to get it in your custom onTouchEvent. You need to debug your view hierarchy – MatPag Jul 07 '20 at 16:18
  • @FotiDim Maybe you can override `dispatchTouchEvent` and `onInterceptTouchEvent` to see the events destinations – MatPag Jul 07 '20 at 16:20
  • I updated my question with the full code. That's it. There is nothing else. – Foti Dim Jul 07 '20 at 16:23
  • Read this answer: https://stackoverflow.com/a/22490810/2910520 check if you can override some of those methods and see the debugger stepping into them (start overriding Activity.dispatchTouchEvent) – MatPag Jul 07 '20 at 16:35