kotlin ViewModel SavedStateHandle临时保存数据
教程使用kotlin语言,使用了Jetpack库中的ViewModel,LiveData,DataBindeing等组件
自己模拟app被后台杀死得情况,开发者选项中勾选不保留活动测试
1.build.gradle(app)中添加
android { dataBinding { enabled = true } }
2.activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <variable name="viewModel" type="com.renchunlin.databindingkt.MyViewModel" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:text="@{String.valueOf(viewModel.getContentNumber())}" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="150dp" android:onClick="@{()->viewModel.add()}" android:text="Button" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
3.MyViewModel.kt
package com.renchunlin.databindingkt import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel /* * class title: * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/8/18. * PS: Not easy to write code, please indicate. */ class MyViewModel(private val handle: SavedStateHandle) : ViewModel() { companion object { const val KEY_NUMBER = "key" } private val number: Int = 0 fun getContentNumber(): MutableLiveData<Int> { if (!handle.contains(KEY_NUMBER)) { handle.set(KEY_NUMBER, number) } return handle.getLiveData(KEY_NUMBER) } fun add() { getContentNumber().value = getContentNumber().value?.plus(1) } }
4.MainActivity.kt
package com.renchunlin.databindingkt import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.ViewModelProvider import com.renchunlin.databindingkt.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private val myViewModel by lazy { ViewModelProvider(this).get(MyViewModel::class.java) } private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.viewModel = myViewModel binding.lifecycleOwner = this } }