I understand pretty well about Android lifecycle. I post here because I've observed one weird behavior, anyway this is my own thought.
My case is like this: One activity will use a simple layout with just a single EditText
. In the activity onCreate
method, i set some default text to the EditText
and in later part of the method, assign a TextWatcher
to the EditText
so whenever user types in anything, i can response in my own way.
Everything is alright until I rotate the screen. The TextWatcher
callback starts to react against the code that initialize the EditText
.
According to the normal code flow, the TextWatcher
is assigned later after initializing text value of the EditText
. so it's not supposed to fire because of the text assignment in the onCreate
method.
Could anyone here explain this?
Prevent Activity to recreated Another most common solution to dealing with orientation changes by setting the android:configChanges flag on your Activity in AndroidManifest. xml. Using this attribute your Activities won't be recreated and all your views and data will still be there after orientation change.
Using ViewModel to Store UI State. The Android team introduced ViewModel and LiveData classes to help save state during configuration changes. A ViewModel stores and manages UI-related data in a lifecycle-conscious manner. Simply put, it allows data to survive configuration changes.
Retain an object during a configuration change ViewModel objects are preserved across configuration changes so they are the perfect place to keep your UI data without having to query them again. For more information about using the ViewModel class in your apps, read the ViewModel overview.
When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them . Android does this so that your application can reload resources based on the new configuration.
Here is why you see this behavior:
Bundle
savedInstanceState
parameter is null.savedInstanceState
parameter.onCreate
returns, Android calls onRestoreInstateState
.id
are trying to restore their state, EditText
restores its state too (actually, that TextView
who restores most of it).onCreate
method is completed) your EditText
control calls setText
on himself in order to restore text that it had just before configuration changed.TextWatcher
that you added in onCreate
method is notified about this change.Just to make this clear, your old TextWatcher, that you added on first call to onCreate
, is not preserved! Its new TextWatcher, that was added on last call to onCreate
, which receives the text change notification.
You can examine TextView.onRestoreInstanceState yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With