Communication between Fragments

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 06:33:12

问题


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


来源:https://stackoverflow.com/questions/12858619/communication-between-fragments

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