从片段中删除片段 [英] Removing a Fragment from a Fragment
问题描述
我有一个Activity
创建了Fragment
,然后此Fragment
创建了另一个Fragment
:
I have an Activity
that creates a Fragment
and then this Fragment
creates another Fragment
:
活动-> Fragment1-> Fragment2
我现在在Fragment2
中,我想通过单击按钮返回到Fragment1
.
I am now in Fragment2
and I'd like to go back to Fragment1
by clicking on a button.
在我的button
的OnClickListener
中,我有:
getActivity().getSupportFragmentManager().beginTransaction().remove(fragment2.this).commit();
这使我进入Activity
.实际上有一种方法可以删除Fragment2
并转到Fragment1
吗?
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!
推荐答案
@AhmedAbidi对您的问题有很好的了解,是的,正确实施popBackStack
可能会解决您的问题.但是无论如何,我想提出一种不同的方法来处理这种情况.
@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.
在Activity
中编写两个公共函数,以在片段之间进行切换.
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();
}
现在从按钮中单击Fragment1
,您可以通过
Now from the button click in your Fragment1
you might launch the Fragment2
via,
((YourActivity) getActivity()).switchToFragment2();
与切换到Fragment1
((YourActivity) getActivity()).switchToFragment1();
这篇关于从片段中删除片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!