屏幕橫豎屏切換或摺疊屏切換時,activity會銷燬而後重建,後面賦值的變量會爲null。 須要onSaveInstanceState保存數據,onCreate 恢復數據。 使用android-state或icepick能使用註解自動保存和恢復,不用每一個變量put 和get。android
android-state和icepickgit
android-stategithub
api 'com.evernote:android-state:1.4.1'
kapt 'com.evernote:android-state-processor:1.4.1'
複製代碼
BaseActivityapi
abstract class BaseActivity() : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
StateSaver.restoreInstanceState(this, savedInstanceState)
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
StateSaver.saveInstanceState(this, outState)
}
}
複製代碼
使用ide
class TestActivity : BaseActivity() {
@State
var username: String? = null
}
複製代碼
icepickthis
implementation 'frankiesardo:icepick:3.2.0'
kapt 'frankiesardo:icepick-processor:3.2.0'
複製代碼
BaseActivityspa
abstract class BaseActivity() : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Icepick.restoreInstanceState(this, savedInstanceState)
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Icepick.saveInstanceState(this, outState)
}
}
複製代碼
使用rest
class TestActivity : BaseActivity() {
@State
@JvmField
var username: String? = null
}
複製代碼