Android make view disappear by clicking outside of it

An easy/stupid way:

  • Create a dummy empty view (let's say ImageView with no source), make it fill parent

  • If it is clicked, then do what you want to do.

You need to have the root tag in your XML file to be a RelativeLayout. It will contain two element: your dummy view (set its position to align the Parent Top). The other one is your original view containing the views and the button (this view might be a LinearLayout or whatever you make it. don't forget to set its position to align the Parent Top)

Hope this will help you, Good Luck !


Find the view rectangle, and then detect whether the click event is outside the view.

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Rect viewRect = new Rect();
    mTooltip.getGlobalVisibleRect(viewRect);
    if (!viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
        setVisibility(View.GONE);
    }
    return true;
}

If you want to use the touch event other place, try

return super.dispatchTouchEvent(ev);