Deleting a fragment by pressing / touching outside:

I have some snippets that are added and removed from dynamic code RelativeLayout. one of the fragments is this ListFragment, and, like my other fragments with the Close and Save buttons, this list contains only the list.

My goal is to close / delete this fragment by clicking it out of place anywhere.

I 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);
}

This closes not full-screen activity when clicked outside, but I just don’t understand how to find the fragment rectangle.

Can someone help and point me in the right direction? Any help would be appreciated.

Thank.

+5
source share
2 answers

Well, I 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 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 );
}
+5
source

RelativeLayout. , RelativeLayout, .

+1

All Articles