简体   繁体   English

保存状态导航抽屉页面(片段)

[英]Save state navigation drawer page (fragment)

I've had a search on SO and can't find anything that works. 我已经搜索过SO,但找不到任何有效的方法。

Here's what I want to do, when I navigate between navigation drawer pages, I want the view to be the same. 这是我想要做的,当我在导航抽屉页面之间导航时,我希望视图保持相同。 So if I go from page A to B, and then from B to A. I expect A to have the same state. 因此,如果我从页面A转到页面B,然后从页面B转到页面A。我希望A具有相同的状态。

In my app, I add some text to fragment A via some button. 在我的应用程序中,我通过一些按钮向片段A添加了一些文本。 When I navigate to fragment B, and then back to A, the text is gone. 当我导航到片段B,然后返回到A时,文本消失了。 I want the text to still be there. 我希望文本仍然存在。

How do I do this? 我该怎么做呢?

I've already tried setRetainState(true). 我已经尝试过setRetainState(true)。 This doesn't work. 这行不通。 I have also made sure that new Fragment() is only called once when going to the page. 我还确保新的Fragment()在转到页面时仅被调用一次。 This also doesn't work. 这也不起作用。

The structure of my navigation drawer is identical to the one shown in the Android documentation. 我的导航抽屉的结构与Android文档中显示的结构相同。

I think, if you have a navigation drawer that you use fragments for each page. 我认为,如果您有一个导航抽屉,则每个页面都使用片段。 On select item in navigation drawer don't recreate the fragment, just pop it from back stack if it exists. 在导航抽屉中的选择项上,不要重新创建片段,只要存在就从后堆栈中弹出即可。

 HomeFragment homeFragment = (HomeFragment) fm.findFragmentByTag(fragmentName);
 if (homeFragment == null) {
     homeFragment = new HomeFragment();
     fm.beginTransaction().addToBackStack(fragmentName).replace(R.id.content_frame, homeFragment, fragmentName).commit();
 } else {
      fm.popBackStackImmediate(fragmentName, 0);
 }

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

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