4

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.

Community
  • 1
  • 1
Mehdi Fanai
  • 4,021
  • 13
  • 50
  • 75

3 Answers3

5

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.
}
Cabezas
  • 9,329
  • 7
  • 67
  • 69
nexus_2006
  • 744
  • 2
  • 14
  • 29
2

You could try using the onDetached() callback of the fragment. This will be called whenever it is removed from its Activity.

Karakuri
  • 38,365
  • 12
  • 84
  • 104
1

Use onAttach() to check when the fragment is attached to the Activity and use onDettach() to check when the fragment is dettached to the activity.

Using the onDettach() you can also check to update or not views, data, etc in this way:

@Override
public void onDetach() {
    super.onDetach();
    synchronized (mLock) {
        mReady = false;
    }
}
Nicolas Jafelle
  • 2,661
  • 2
  • 24
  • 30
  • What `synchronized(mLock) ` is for, in your code? pls add some more code if possible.Thank you – Mehdi Fanai May 31 '13 at 09:51
  • It is related to refresh or not an asyncktask. For example if the fragment is dettached but a background task finish in this state, it tries to update the views for example textView.setText(newStringValue). With this condition if mReady is false avoid this behaviour. – Nicolas Jafelle May 31 '13 at 13:48
  • You don't need synchronization, since onDetach and onPostExecute is called on the same thread – Korniltsev Anatoly Jan 12 '16 at 09:47