繁体   English   中英

替换片段时addToBackstack不起作用

[英]addToBackstack not working when replacing fragments

我有一个问题,我在替换它时在我的片段上调用addToBackStack ,但当我按回去返回到该片段时,它不会返回,它只是关闭我的应用程序。

Fragment fragmentWebView = new MyWebView();
transaction.replace(R.id.content_frame, fragmentWebView);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();

我在这里做错了吗? 一切看起来都很好。

尝试将此代码添加到您的活动中

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0 ){
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

看着这里

希望能帮助到你

我不确定它是否相关但你不应该使用new创建你的片段,请参阅StackOverflow上的这篇文章

你应该调用addToBackStack(MyWebView.class.getName()); 并建议您检查您的片段是否存在。 complet事务可能是这样的:

Fragment fragmentWebView = getFragmentManager().findFragmentByTag(MyWebView.class.getName());
if (fragmentWebView == null)
     fragmentWebView = new MyWebView();

transaction.replace(R.id.content_frame, fragmentWebView, MyWebView.class.getName());
transaction.addToBackStack(MyWebView.class.getName());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();

现在,您可以通过标记(MyWebView.class.getName())识别您的片段。 希望它能帮到你!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM