Android retain callback state after configuration change
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 late开发者_JAVA技巧r 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?
Here is why you see this behavior:
- When 'onCreate' method is called first time, it has no saved state. Which means
Bundle
savedInstanceState
parameter is null. - When configuration changed, Android paths non-null value in
savedInstanceState
parameter. - After configuration is changed, and
onCreate
returns, Android callsonRestoreInstateState
. - By default, all views that have
id
are trying to restore their state,EditText
restores its state too (actually, thatTextView
who restores most of it). - At some place during state restoration (but after
onCreate
method is completed) yourEditText
control callssetText
on himself in order to restore text that it had just before configuration changed. - Your new
TextWatcher
that you added inonCreate
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.
When ever you rotate the device the onCreate method of activity called again.if you want to prevent to call onCreate when rotating the device do the following code in the Manifest
android:configChanges="orientation|keyboardHidden"
and in your activity
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
{
}
else if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT)
{
}
}
精彩评论