I have some fragments that are added and removed from a RelativeLayout
dynamically using code. one of the Fragments is a ListFragment
, and as oppose to other my fragments that have a Close and Save Buttons this one contains only a list.
My goal is to close/remove this fragment by clicking outside of it on any place in the activity.
I have found the following code:
@Override
public boolean onTouchEvent(MotionEvent event) {
// I only care if the event is an UP action
if (event.getAction() == MotionEvent.ACTION_UP) {
// create a rect for storing the window rect
Rect r = new Rect(0, 0, 0, 0);
// retrieve the windows rect
this.getWindow().getDecorView().getHitRect(r);
// check if the event position is inside the window rect
boolean intersects = r.contains((int) event.getX(), (int) event.getY());
// if the event is not inside then we can close the activity
if (!intersects) {
// close the activity
this.finish();
// notify that we consumed this event
return true;
}
}
// let the system handle the event
return super.onTouchEvent(event);
}
That closes a not full-screen activity when clicking outside of it, but i just don't seem to understand how do I find my fragment rectangle.
Could some one assist and point me in the right direction? Any help would be appreciated.
Thanks.
Well I have finally figured this out:
@Override
public boolean onTouchEvent ( MotionEvent event )
{
// I only care if the event is an UP action
if ( event.getAction () == MotionEvent.ACTION_UP )
{
//and only is the ListFragment shown.
if (isListFragmentShown)
{
// create a rect for storing the fragment window rect
Rect r = new Rect ( 0, 0, 0, 0 );
// retrieve the fragment's windows rect
currentFragment.getView().getHitRect(r);
// check if the event position is inside the window rect
boolean intersects = r.contains ( (int) event.getX (), (int) event.getY () );
// if the event is not inside then we can close the fragment
if ( !intersects ) {
Log.d(TAG, "pressed outside the listFragment");
FragmentTransaction fragmentTransaction;
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(currentFragment).commit();
// notify that we consumed this event
return true;
}
}
}
//let the system handle the event
return super.onTouchEvent ( event );
}
You can add click listener to your container RelativeLayout. If fragment is up about action then activate your RelativeLayout's listener so listener only works while fragment exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With