Search code examples
androidandroid-fragmentsfragmenttransaction

how to wait until a fragment is removed


I have an activity with dynamic fragments in it. I need to run some code after a fragment is removed but remove(myFragment).commit() is executed asynchronously and i cant know when exactly the fragment is removed.Here is my code:

final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(myFragment).commit();
//wait until the fragment is removed and then execute rest of my code

From the documentation:

public abstract int commit ()

Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.


Solution

  • What if you use the fragment's onDetach method to call the activity and tell it its done?

    class MyFrag extends Fragment {
    
        private Activity act;
    
        @Override
        public void onAttach(Activity activity) {
            act = activity;
        }
    
        @Override
        public void onDetatch() {
            act.fragGone();
        }
    }
    

    And in the activity:

    public void fragGone() {
        //do something, update a boolean, refresh view, etc.
    }