Vipul Purohit
Vipul Purohit

Reputation: 9827

Fragment onStart and onCreateActivity called after back button press

Scenario:
I have a single Activity in which I have multiple fragments and I'm replacing one fragment with another using fragment transaction and add them to BackStack. I am doing JSON parsing and network related task on some fragments.

Problem: My problem is that after replacing the fragment when I press back button to nevigate to last fragment the onStart and onActivityCreated methods called again. My code in these events execute each time I navigate to that fragment by using back button

But Any value in EditText remain same in even after replacing the fragment and coming back to it using back button.

Why onStart and onActivityCreated executed each time? Is there any method where I can put my code which do not execute after coming back to fragment?

UPDATE Basically I want to set a button text once fragment is created. User can change that text. but when I return back to that fragment the users value change with the default text which I set on fragment creation time.

Thanks

Upvotes: 3

Views: 5681

Answers (1)

Mukesh Kumar Singh
Mukesh Kumar Singh

Reputation: 4522

You can put your code to run only one time at fragment creation in onCreate() of fragment..

onCreate()

The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.

See the life cycle of fragment.enter image description here

You can also get more details here

Upvotes: 5

Related Questions