我有一个在 XML 中设置了某个默认值的静态文本视图。后来,我将该变量设置为其他值,但只要方向发生变化,静态变量的值就会恢复为默认值,即使我没有重新初始化它。为什么会这样?即使在 onCreate() 被调用后,值不应该保持不变吗?
3 回答
When onCreate()
gets called I'm guessing you also call setContentView()
as normal. This redraws all of the Views
with the default values. You need to handle the configuration changes
See this answer of mine on how to handle it. The recommended way is to use onSavedInstanceState
but I normally handle it myself and haven't had any problems...yet
在方向更改期间,Android 会重新创建所有布局。要保存小部件的状态,您可以简单地将一个分配id
给 TextView 元素:
<TextView
android:id="@+id/tv_caption"
...
/>
This has to do with the lifecycle of an Android app. Whenever you rotate, your application goes through all the lifecycle method calls. You need to store the current state within a Bundle and restore that data in your onCreate
after the rotation has occurred.