Android 在配置更改后保留回调状态
我非常了解 Android 生命周期。我在这里发帖是因为我观察到一种奇怪的行为,无论如何这是我自己的想法。
我的情况是这样的:一个活动将使用只有一个 EditText
的简单布局。在活动 onCreate
方法中,我为 EditText
设置了一些默认文本,并在该方法的后面部分,为 TextWatcher
分配了一个 TextWatcher
。 >EditText 因此,每当用户输入任何内容时,我都可以以自己的方式进行响应。
一切都很好,直到我旋转屏幕。 TextWatcher
回调开始对初始化 EditText
的代码做出反应。
按照正常的代码流程,TextWatcher
是在初始化EditText
的文本值之后分配的。因此,由于 onCreate
方法中的文本分配,它不应该被触发。
这里有人能解释一下吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是您看到此行为的原因:
Bundle
savedInstanceState
参数为 null。savedInstanceState
参数中路径非空值。onCreate
返回,Android 调用onRestoreInstateState
。id
的视图都会尝试恢复其状态,EditText
也会恢复其状态(实际上,恢复大部分内容的TextView
它)。onCreate
方法完成之后),您的EditText
控件对自身调用setText
以恢复它所具有的文本就在配置更改之前。onCreate
方法中添加的新TextWatcher
会收到有关此更改的通知。只是为了澄清这一点,您在第一次调用
onCreate
时添加的旧 TextWatcher 不会被保留!它的新 TextWatcher 是在上次调用onCreate
时添加的,它接收文本更改通知。您可以检查 TextView.onRestoreInstanceState 自己。
Here is why you see this behavior:
Bundle
savedInstanceState
parameter is null.savedInstanceState
parameter.onCreate
returns, Android callsonRestoreInstateState
.id
are trying to restore their state,EditText
restores its state too (actually, thatTextView
who restores most of it).onCreate
method is completed) yourEditText
control callssetText
on himself in order to restore text that it had just before configuration changed.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 toonCreate
, which receives the text change notification.You can examine TextView.onRestoreInstanceState yourself.
当您旋转设备时,活动的 onCreate 方法会再次调用。如果您想防止在旋转设备时调用 onCreate,请在清单
和活动中执行以下代码
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
and in your activity