Joe
Joe

Reputation: 3921

ConstraintLayout stealing taps from setOnClickListener

I have created an activity that will be used as a screen to display a custom-designed modal. The entire background of this activity will be a 30% black overlay view that should be tappable to dismiss the activity.

Here's a screen of the simple layout:

modal

In onCreate, I added a setOnClickListener to the overlay:

overlayView.setOnClickListener {
        println("tapped")
}

The overlay is receiving taps, which is desired, however the white 'modal' view is also receiving taps, which is not desired.

As you can see from the component tree in the above screenshot, I'm using a view (overlayView), and then above it, using a ConstraintLayout with a nested textView. I would think that since the white modal is above the overlayView, it would not be receiving taps from overlayView.

How can I structure / organize my component tree so that I can detect taps from just the overlayView, and not the white modal?

Upvotes: 0

Views: 77

Answers (1)

Ben P.
Ben P.

Reputation: 54234

In general, touch events will go "through" views until they find one that actually handles the event. In this case, even though you're tapping on the modal view, the click event will go to the background overlay because the modal view doesn't do anything to intercept the event.

You can solve this by adding a do-nothing click listener to the modal view:

modalView.setOnClickListener { }

This causes the modal view to receive any click events on it and handle them, stopping them from going "through" to the background overlay view.

Upvotes: 1

Related Questions