I have a fragment that I need to close when clicking outside of it, this is the code I have:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Rect dialogBounds = new Rect();
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragmentoLeyes);
if (currentFragment!=null) {
currentFragment.getView().getHitRect(dialogBounds);
if (currentFragment instanceof VideoFragment) {
if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
onBackPressed();
}
}
}
return super.dispatchTouchEvent(ev);
}
The problem with the code is that when I click inside the fragment, it closes it and I only need it to close when the click or tap is outside of it.
The best thing in this case is to override the method
onTouchEvent()
, when touching itFragment
detects the coordinates by means of aRect
:and this will determine if you are tapping outside of the
Fragment
to proceed to remove it.This would be an example: