[英]Retain Fragment's Main View from OnCreateView After OnDestroyView is called
I have a main Activity
that contains a ViewPager
with 4 tabs. 我有一个主要的
Activity
,其中包含一个带有4个标签的ViewPager
。 Each tab has a fragment
inside of it. 每个选项卡内部都有一个
fragment
。 I implement an ActionBar.TabListener
on the main Activity
. 我在主
Activity
上实现了ActionBar.TabListener
。 In the OnTabSelected
method, I call a custom fragment.refresh
method on the selected fragment
so that I refresh and update the fragment
from the server. 在
OnTabSelected
方法中,我对所选fragment
调用了一个自定义fragment.refresh
方法,以便从服务器刷新和更新该fragment
。 The refresh
method resets the data. refresh
方法将重置数据。
When I close the app and, after a while, I re-open it, and I get a NullPointerException
on the main View returned from OnCreateView
for the fragment
. 当我关闭应用程序并过一段时间后,我将其重新打开,并且在
OnCreateView
返回的fragment
的主视图上收到NullPointerException
。
My question is: How do I retain the main view for the fragment after OnDestroyView
is called? 我的问题是: 调用
OnDestroyView
之后,如何保留片段的主视图? Or, How do I make sure that refresh
is called after OnCreateView
has been called? 或者, 如何确保在调用
OnCreateView
之后调用refresh
? (Should I use a flag with a while loop)? (我应该在while循环中使用一个标志)吗?
You could try putting your custom fragment.refresh() in your fragment.onResume(). 您可以尝试将自定义fragment.refresh()放入fragment.onResume()中。 This way the refresh would be automatically called before the fragment is shown to the user.
这样,将在片段显示给用户之前自动调用刷新。
If you really want to update the fragment only when the user click on the tab you could do something like that: 如果您只想在用户单击选项卡时才更新片段,则可以执行以下操作:
refresh(){
if(getActivity()!=null && !isDetached()){ // check if fragment is visible
refreshData(); // refresh data
}else{
needRefresh=true; // set flag for refresh
}
}
and 和
onCreate(...){
...
if(needRefresh){
needRefresh = false;
refreshData();
}
}
I think you should go with the first solution because i'm afraid this second solution might not be flawless. 我认为您应该使用第一个解决方案,因为恐怕第二个解决方案可能并非完美无缺。
I hope I am understanding you correctly. 希望我能正确理解您。 First your statement,
首先你的陈述,
How do I retain the main view for the fragment after OnDestroyView is called?
调用OnDestroyView之后,如何保留片段的主视图?
You cannot cache the view object in memory, especially after OnDestroyView(). 您不能在内存中缓存视图对象,尤其是在OnDestroyView()之后。
Answering your 2nd question, you could call your custom refresh() at an override method in Fragment like: 回答您的第二个问题,您可以在Fragment中的覆盖方法上调用自定义的refresh(),例如:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
refresh();
...
}
OnCreateView()
. OnCreateView()
之后调用refresh OnCreateView()
。 onTabSelected
(). onTabSelected
()。 But it seems you're not interested in this.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.