3

I have default Master-Detail flow, which was created automatically when creating new project. My question is. When I add a button to detail side. Is there a way to update my list side by pressing that button ? In other words, can ItemDetailFragment and ItemListFragment communicate ?

Michal
  • 15,429
  • 10
  • 73
  • 104
slezadav
  • 6,104
  • 7
  • 40
  • 61

1 Answers1

6

Yes just communicate through the activity with a listener.

Your activity:

public class MyActivity extends FragmentActivity implements OnFragmentClickListener {
    @Override
    public void OnFragmentClick(int action, Object object) {
        switch(action) {
        }
    }
}

The listener class:

    public interface OnFragmentClickListener {
        public void OnFragmentClick(int action, Object object);
    }

Your fragments will then have following somewhere in code in order to implement the interface:

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentClickListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement listeners!");
        }
    }

Then your fragments communicate with each other like this: fragmentA -> activity -> fragmentB. Your activity can call methodes directly on the fragments without worrying about synchronization problems.

Example of a call from fragment a:

mListener.OnFragmentClick(GLOBAL_ACTION_KEY someObject);

Activity then handle:

public class MyActivity extends FragmentActivity implements OnFragmentClickListener {
    @Override
    public void OnFragmentClick(int action, Object object) {
        switch(action) {
            case GLOBAL_ACTION_KEY:
                // you call fragmentB.someMethod();
                break;
        }
    }
}
Warpzit
  • 27,966
  • 19
  • 103
  • 155
  • Which one does your fragment sit in? If the fragments sit in each their activity you might want to consider communicating through a static class or something similar. Could you perhaps describe how your hierarchy is? – Warpzit Oct 12 '12 at 12:23