[英]Swaping Fragments with actionbar tabs
I have 3 fragments in my app divided into 3 tabs respectively [1] [2] [3]. 我的应用程序中有3个片段,分别分为3个标签[1] [2] [3]。
Imagine that I use a button on the fragment [1] that will make a TextView with an initial text "X" becomes a "Y" Ex: tv.setText("I'm a new text");
想象一下,我在片段[1]上使用了一个按钮,它将使带有初始文本“ X”的TextView变成“ Y”例如:
tv.setText("I'm a new text");
So when I navigate between tabs and I return to the tab [1], the TextView is back with the original text. 因此,当我在选项卡之间导航并返回到选项卡[1]时,TextView将返回原始文本。 It is as if the onCreate() was calling again.
就像onCreate()再次被调用一样。
I wish somehow that onStop() was not called in my fragments, retaining all the properties of my views (such as text, visibility etc.) in memory while I swap between tabs. 我希望以某种方式在片段中不调用onStop(),以便在选项卡之间进行交换时将视图的所有属性(例如文本,可见性等)保留在内存中。
Thanks! 谢谢!
---- EDIT! ---- 编辑! ----
----
Well, I found the solution to what I wanted! 好吧,我找到了想要的解决方案! It's simple enough I declare that:
我声明很简单:
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setOffscreenPageLimit(3); //Number of fragments that I wish to store in memory
well, that happens because the onCreate is actually being called. 好吧,这是因为onCreate实际上被调用了。 If I was you, I would use a ViewPager.
如果我是你,我将使用ViewPager。 That way, just setting the offScreenElementNumber to 2 you'll have all fragments instantly loaded and they will preserve their state!
这样,只需将offScreenElementNumber设置为2,即可立即加载所有片段,它们将保留其状态!
take a look at this: 看看这个:
http://tamsler.blogspot.com.es/2011/10/android-viewpager-and-fragments.html http://tamsler.blogspot.com.es/2011/10/android-viewpager-and-fragments.html
onCreate method is being called again. 再次调用onCreate方法。 You can save the values by overriding onSavedInstanceState and get them back in onActivityCreated method.
您可以通过覆盖onSavedInstanceState来保存值,然后将其恢复为onActivityCreated方法。 For example lets save boolean(you can save whatever you want - string, int etc..):
例如,让我们保存布尔值(您可以保存所需的任何内容-字符串,整数等。):
save the value: 保存值:
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean("booleanValue", true);
}
restore the value (you can call this in onCreate as well): 恢复值(您也可以在onCreate中调用它):
protected void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey("booleanValue")) {
boolean myBoolean = savedInstanceState.getBoolean("booleanValue");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.