Detect click on dialog in Android

I have a dialog:

final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.location_dialog);
dialog.setTitle("My dialog");
dialog.setMessage("My dialog content");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.show();

I want to be able to detect strokes on top of the lines of a dialog box. I can easily detect any touches outside the dialog box using the build method

dialog.setCanceledOnTouchOutside(true);

But how can I detect strokes inside this area? detect touches only in the area in red.

+5
source share
1 answer

Create a Dialog extension and override the method you need: dispatchTouchEvent or onTouchEvent (From the docs: this is most useful for handling touch events that occur outside the borders of a window where there is no view to receive it.)

Updated:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Rect dialogBounds = new Rect();
    getWindow().getDecorView().getHitRect(dialogBounds);

    if (dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
        Log.d("test", "inside");
    } else {
        Log.d("test", "outside");
    }
    return super.dispatchTouchEvent(ev);
}
+8
source

All Articles