As i understand it, would it not be better to create a fragments event listeners in the fragments onCreate? If it is done in onCreateView it would have to be redone everytime the fragment comes back into view (onResume())? Would it make a difference where it is set?
Asked
Active
Viewed 2.3k times
2
-
Which events are you talking about? – Kevin Coppock Jan 17 '14 at 06:37
-
It would mostly be onclick events. I think I have filled that gap in my understanding now, but would still be interested to know which events you would set in onCreate? Does one get any events other that UI events? If possible a link would be appreciated! – Chris Jan 17 '14 at 07:05
2 Answers
10
1) yes it can be better
2) yes you are correct, as event listener is initialised there than the process will be repeated here
3) please have a close look at life-cycle method
4)it always makes difference where you are using and when you are initializing.

Jitesh Upadhyay
- 5,244
- 2
- 25
- 43
-
I see what you mean. I was under the impression that onResume would call onCreateView. I've found the following link quite nice, incase someone else ever wonders about the same thing: https://www.inkling.com/read/programming-android-mednieks-1st/chapter-11/visualizing-the-fragment-life – Chris Jan 17 '14 at 07:13
4
An event is set on a view and hence is restored when the view is restored. For example, lets say we set a listener on a button in a fragment that is created in onCreateView. If at some point of time, if the fragment is restored (without a call to onCreateView), the button is restored along with the listener that is set. The same goes for setting a text/background for a button - you don't have to reset the text/background each time the fragment is resumed.

Srikanth
- 2,014
- 19
- 22
-
I see, I missed the part where the associated view gets instantiated in onCreateView. I was also under the impression that if the view is restored it would recall the onCreateView method every single time, which was wrong of me.Thanks for explaining that to me! – Chris Jan 17 '14 at 07:10
-
You are not wrong in thinking that the onCreateView is called every single time the fragment gets restored. onCreateView does get called every single time the fragment gets restored. In my answer, I am taking the hypothetical case of onCreateView not being called, which actually never happens. Refer this - http://stackoverflow.com/questions/18428152/stop-fragment-from-recreated-after-resume – Srikanth Jan 17 '14 at 07:43