配置更改后的And​​r​​oid保留回调状态回调、状态、And、oid

由网友(智商都拿去卖萌了)分享简介:据我所知pretty的还有关于Android的生命周期。我张贴在这里,因为我发现的一个奇怪的现象,反正这是我自己的想法。I understand pretty well about Android lifecycle. I post here because I've observed one weird behav...

据我所知pretty的还有关于Android的生命周期。我张贴在这里,因为我发现的一个奇怪的现象,反正这是我自己的想法。

I understand pretty well about Android lifecycle. I post here because I've observed one weird behavior, anyway this is my own thought.

我的情况是这样的:一个活动将使用一个简单的布局只是一个单一的的EditText 。在活动的onCreate 的方法,我设置一些默认的文本到的EditText 和方法的最新部分,分配 TextWatcher 的EditText 所以每当在任何用户类型,我可以回应我自己的方式。

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.

一切正常,直到我旋转屏幕。该 TextWatcher 回调开始在code表示初始化发生反应的EditText

Everything is alright until I rotate the screen. The TextWatcher callback starts to react against the code that initialize the EditText.

根据正常的code流动,在 TextWatcher 分配后初始化的EditText 。所以它不应该因为的onCreate 法文本分配的火。

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:

当的onCreate方法被调用一次,它没有保存的状态。这意味着捆绑 savedInstanceState 参数为null。 在当前的配置改变,在 savedInstanceState 参数Android的路径非空值。 在配置完成后改变,而​​的onCreate 的回报,Android的电话 onRestoreInstateState 。 在默认情况下,已 ID 正在努力恢复自己的状态,所有的意见,的EditText 恢复其状态太(事实上,这的TextView 谁恢复大部分)。 在中状态恢复一些地方(但在的onCreate 方法完成),你的的EditText 控制调用的setText 在自己身上,以恢复文本,它有配置改变之前。 您的新的 TextWatcher 您在的onCreate 方法添加被告知这一变化 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 calls onRestoreInstateState. By default, all views that have id are trying to restore their state, EditText restores its state too (actually, that TextView who restores most of it). At some place during state restoration (but after onCreate method is completed) your EditText control calls setText on himself in order to restore text that it had just before configuration changed. Your new TextWatcher that you added in onCreate method is notified about this change.

只是为了说明这一点,你的旧的TextWatcher,所添加的第一个电话到的onCreate ,是不是preserved!它的新的TextWatcher,这是加在最后呼吁的onCreate ,它接收文本更改通知。

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.

您可以检查 TextView.onRestoreInstanceState 的自己。