ViewModel以注重组件生命周期的方式存储和管理页面相关的数据。ViewModel让Activity未设置configChanages="orientation|screenSize"属性时,设备发生旋转后,页面数据得以继续留存。
RViewModel类:
class RViewModel : ViewModel() { internal var count: Int = 0 }
MainActivity类,未设置configChanages属性:
class MainActivity : AppCompatActivity() { private var _rViewModel: RViewModel? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) _rViewModel = ViewModelProvider(this).get(RViewModel::class.java) button.setOnClickListener { _rViewModel?.count = (_rViewModel?.count ?: 0) + 1 countText.text = _rViewModel?.count?.toString() ?: "0" } } override fun onStart() { super.onStart() Log.d("main", "${_rViewModel?.count?.toString()}") countText.text = _rViewModel?.count?.toString() ?: "0" } }
结果:
D/main: 1 D/main: 2 D/main: 3 D/main: 4 D/main: 5 D/main: 旋转后 D/main: 5
原文:https://www.cnblogs.com/naray/p/15196253.html