Search code examples
androidandroid-fragmentsmaster-detailactivity-finish

How to finish fragment in Master/Detail flow?


I dont know how to do this the right way. I have a master/detail flow, now I perform an action in the detail that needs to finish it, but of course, detail fragment should be unaware of wether its wrapped by a single or dual pane activity.

So how should I do this? I was thinking about a callback that both activities would implement and the single pane would just finish it self and therefore finishing the fragment, and the dual pane would just pop the fragment.

Is this a good idea? Having callbacks from the detail fragment? Isnt this much overhead?

Thanks


Solution

  • now I perform an action in the detail that needs to finish it

    That is unusual flow for the master/detail pattern. Normally, the detail persists until the user taps on something else in the master list. I could see your proposed flow for a delete operation on the item being viewed, though.

    I was thinking about a callback that both activities would implement and the single pane would just finish it self and therefore finishing the fragment, and the dual pane would just pop the fragment.

    That is a fine answer.

    Isnt this much overhead?

    No. Define an interface that all activities hosting your fragment must implement. You might consider using the contract pattern to help enforce that:

    import android.app.Activity;
    import com.actionbarsherlock.app.SherlockFragment;
    
    // from https://gist.github.com/2621173
    
    public abstract class ContractFragment<T> extends SherlockFragment {
      private T mContract;
    
      @SuppressWarnings("unchecked")
      @Override
      public void onAttach(Activity activity) {
        try {
          mContract=(T)activity;
        }
        catch (ClassCastException e) {
          throw new IllegalStateException(activity.getClass()
                                                  .getSimpleName()
              + " does not implement "
              + getClass().getSimpleName()
              + "'s contract interface.", e);
        }
        super.onAttach(activity);
      }
    
      @Override
      public void onDetach() {
        super.onDetach();
        mContract=null;
      }
    
      public final T getContract() {
        return mContract;
      }
    }
    

    (code based on a gist from Jake Wharton of ActionBarSherlock fame)

    Here, T is the name of the interface. Your fragment would inherit from this and call getContract() to retrieve the interface implementation object, on which you call your callback method. Runtime overhead will be on the order of a few dozen instructions at most -- nothing you will need to worry about.