How to prevent calling onCreateView when back button pressed in fragment in android

假装没事ソ 提交于 2020-01-01 04:12:07

问题


In my application, I have tabbar functionality. In one tab i am displaying server data in lisview, and on clicking on that detail page for that list item will be open in new fragment.

But when I press back button from that detail page, every time oncreateview called of previous page, so every time listview created and new fetches new server data. So how to prevent such and just display previous state when back button press?


回答1:


I know it has been too long to give this answer but what i am guessing is you are replacing your fragment with other one. I mean to say is you are using

ft.replace(R.id.realTabContent, fragment);

to move to other fragment which is you are using in your onItemClick so simple solution is use

ft.add(R.id.realTabContent, fragment);

instead of replacing your fragment.

Understand the difference between replace and add. This will solve your problem.

Replace : it will replace the original fragment and re-create the view when you come back
Add : it will just add a new fragment to stack.

Hope this will help someone who is facing the same problem...




回答2:


I don't think prevent calling onCreateView is a good idea, beside if the function is not called, there will be exception, so NO, you shouldn't. Instead of doing that, I suggest you move your "listview created and new fetches new server data" into another place where you can call explicitly (when you want, where you want, onCreate() is a good place), don't put it in onCreateView(). Hope this helps.




回答3:


You should cache your data objects apart from view variables as their references needs to be updated if you are fetching any data from server and don't want to make a call again then use branching to branch out that code.

Create an init() method where you do all initialization and server calls and logically branch out call to init() method whenever you don't want to call init().



来源:https://stackoverflow.com/questions/18140549/how-to-prevent-calling-oncreateview-when-back-button-pressed-in-fragment-in-andr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!