Communication between Fragments

家住魔仙堡 提交于 2019-11-28 11:40:01

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;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!