Removing a Fragment from a Fragment

别等时光非礼了梦想. 提交于 2019-12-25 04:04:46

问题


I have an Activity that creates a Fragment and then this Fragment creates another Fragment:

Activity -> Fragment1 -> Fragment2

I am now in Fragment2 and I'd like to go back to Fragment1 by clicking on a button.

In my OnClickListener of my button I have:

getActivity().getSupportFragmentManager().beginTransaction().remove(fragment2.this).commit();

This brings me to the Activity. Is there actually a way to just remove Fragment2 and go to Fragment1?

Thank you in advance for your time, I could not find any suitable info online!


回答1:


@AhmedAbidi has a nice insight to your problem and yes, implementing popBackStack properly may solve your problem. But anyway, I would like to suggest a different approach to handle this type of situations.

Write two public functions in your Activity to switch between your fragments.

public void switchToFragment1() {
    getSupportFragmentManager().beginTransaction()
        .replace(R.id.fragment_container, new Fragment1()).commit();
}

public void switchToFragment2() {
    getSupportFragmentManager().beginTransaction()
        .replace(R.id.fragment_container, new Fragment2()).commit();
}

Now from the button click in your Fragment1 you might launch the Fragment2 via,

((YourActivity) getActivity()).switchToFragment2();

And the same thing while switching to Fragment1

((YourActivity) getActivity()).switchToFragment1();



回答2:


Your question needs more code for clarity.

Is Fragment1 adding Fragment2 via getSupportFragmentManager() or getChildFragmentManager()? Presumably it appears you are doing the former, and if so, you are incorrectly using the Fragment API. Fragments are not supposed to know about each other, per Android's Fragment Documentation:

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

You should therefore implement the appropriate listeners to communicate from Fragment1 to Activity, which can then decide where/when to add Fragment2 -- then properly utilize the back stack functionality of getSupportFragmentManager().addToBackStack()... with getSupportFragmentManager().popBackStack(). See Android Documentation on Back Navigation for Fragments for further explanation.



来源:https://stackoverflow.com/questions/41127315/removing-a-fragment-from-a-fragment

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