Communication between Fragments

2019-01-19 06:59发布

问题:

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 ?

回答1:

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