Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect click over a dialog window 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's content");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.show();

I want to be able to detect touches over and outside the dialog box's lines. I can easily detect any touches outside the dialog box area with the build-in method

dialog.setCanceledOnTouchOutside(true);

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

like image 379
Stefan Doychev Avatar asked Aug 16 '11 12:08

Stefan Doychev


1 Answers

Create an extension of Dialog and override necessary method: dispatchTouchEvent or onTouchEvent (From docs: This is most useful to process touch events that happen outside of your window bounds, 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);
}
like image 139
Flavio Avatar answered Oct 17 '22 11:10

Flavio