viewModel简单应用_保存数据,以供屏幕旋转创建新的Activity/Fragment时取得旋转前的数据(计数器为例)

配置模块gradle.build依赖

主要时viewModel相关的声明周期依赖
在这里插入图片描述

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-android-extensions'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.zjgsu.cxxu.testviewmodel"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

MainActivity.kt

注意使用viewModelProvider()及其方法get()来取得对应的viewModel子类的实例(以取用保存其中的数据)

package ...

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    /*member var:the MainViewModel is subclass of the ViewModel
    * to access the variable(instance) conveniently:*/
    private lateinit var viewModel: MainViewModel

    /**
     *
    androidx.fragment.app.FragmentActivity

    onCreate():Perform initialization of all fragments.
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        /**
         * androidx.lifecycle.ViewModelProvider
         * public ViewModelProvider(@NonNull @NotNull androidx.lifecycle.ViewModelStoreOwner owner)
        Creates ViewModelProvider. This will create ViewModels and retain them in a store of the given ViewModelStoreOwner.
         */
        /**
         * public <T extends androidx.lifecycle.ViewModel> T get(@NonNull Class<T> modelClass)
        Returns an existing ViewModel or creates a new one in the scope
        (usually, a fragment or an activity), associated with this ViewModelProvider.
         应对屏幕旋转时,activity/fragment的销毁重建:(从我们建立的VieModel的子类MainViewModel.kt处获取保存的数据,重新创建视图
         在这个例子中,MainViewModel中存放这核心数据(由其中的计数器变量counter来保存数据值)*/
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        /*listen the click event:*/
        plusOneBtn.setOnClickListener {
            viewModel.counter++
            refreshCounter()
        }
        /*this comment is for the initial call of the OnCreate the display the initial value of the counter value
        * rather than other strings
        * after the refreshCounter(),the code will go into the method of AppCompatActivity and so on to start thread */
        refreshCounter()
    }

    /**
     * refresh textView to display in the UI;
     * after the counter updated in the viewModel instance:
     */
    private fun refreshCounter() {
        infoText.text = viewModel.counter.toString()
    }
}

MainViewModel.kt

package ...

import androidx.lifecycle.ViewModel

class MainViewModel : ViewModel() {
    var counter=0
}

main_activity.xml


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/plusOneBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.207" />

    <TextView
        android:id="@+id/infoText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="72dp"
        android:layout_marginEnd="196dp"
        android:layout_marginRight="196dp"
        android:text="infoText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
posted @ 2021-05-09 13:59  xuchaoxin1375  阅读(12)  评论(0)    收藏  举报  来源