Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 859
Mihir Shah Avatar asked Aug 09 '13 05:08

Mihir Shah


People also ask

How do I disable back press in fragment?

Here is the new way you can manage your onBackPressed() in fragment with the new call back of activity: // Disable onBack click requireActivity(). onBackPressedDispatcher. addCallback(this) { // With blank your fragment BackPressed will be disabled. }

What is the difference between onCreate () and onCreateView () lifecycle methods in fragment?

onCreate is called on initial creation of the fragment. You do your non graphical initializations here. It finishes even before the layout is inflated and the fragment is visible. onCreateView is called to inflate the layout of the fragment i.e graphical initialization usually takes place here.

What are the differences between onCreate () onCreateView () and onActivityCreated () in fragments and what would they each be used for?

onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.


1 Answers

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...

like image 117
InnocentKiller Avatar answered Oct 17 '22 18:10

InnocentKiller