Kotlin: Jetpack — ViewModel简单应用

ViewModel 概览 Android Jetpack 的一部分。

ViewModel 类是一种业务逻辑或屏幕级状态容器。它用于将状态公开给界面,以及封装相关的业务逻辑。 它的主要优点是,它可以缓存状态,并可在配置更改后持久保留相应状态。这意味着在 activity 之间导航时或进行配置更改后(例如旋转屏幕时),界面将无需重新提取数据。

1.导包:

Kotlin 复制代码
    //viewModel包
    // https://mvnrepository.com/artifact/androidx.lifecycle/lifecycle-viewmodel-ktx
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1'


    //runtimeOnly 用于声明一个只在运行时需要的依赖。这意味着这个依赖在编译时不需要,但在运行时需要。
    // 设为runtimeOnly 在编译时会提示有些包找不到比如 viewModels 提示没有  解决方法改为 implementation
    //implementation  依赖项作为编译和运行时的依赖。这意味着这个依赖在编译和运行时都是可见的。
    //工具类实现viewModel创建简化开发 2个包
    // https://mvnrepository.com/artifact/androidx.fragment/fragment-ktx
    implementation  'androidx.fragment:fragment-ktx:1.6.1'
    // https://mvnrepository.com/artifact/androidx.activity/activity-ktx
    implementation  'androidx.activity:activity-ktx:1.6.1'

2.ViewModel() 的创建

写个类实现 ViewModel()

Kotlin 复制代码
package com.example

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel

/**
 * ViewModel() 的创建
 * AndroidViewModel() 子类
 */
class MyviewModel : ViewModel() {
    //初始化块
    init {
        Log.i("TAG", ": MyviewModel ViewModel 初始化")
    }

    //internal  只能在同一个模块或库中被访问,而不能在其他模块或库中被访问。
    internal fun getName(): String {
        return "---MyviewModel getName()方法-${System.currentTimeMillis()}"
    }

    //重新销毁方法
    override fun onCleared() {
        super.onCleared()
        Log.i("TAG", ": MyviewModel onCleared 销毁方法")
    }
}

//AndroidViewModel(private val application: Application) : ViewModel()
class MyviewModelTwo(application: Application) : AndroidViewModel(application) {
    //初始化块
    init {
        Log.i("TAG", ": MyviewModelTwo AndroidViewModel 初始化")
    }

    fun getName(): String {

        return "---MyviewModelTwo getName()方法-${System.currentTimeMillis()}"
    }

    //重新销毁方法
    override fun onCleared() {
        super.onCleared()
        Log.i("TAG", ": MyviewModelTwo onCleared 销毁方法")
    }


}

3.ViewModel 的3种使用方法

MainActivity

Kotlin 复制代码
package com.example

import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelProvider



class MainActivity : AppCompatActivity() {
    //viewmodel使用1.代理 by ViewModelLazy 返回Lazy<VM>
    val vm1: MyviewModel by ViewModelLazy<MyviewModel>(
        MyviewModel::class,
        { viewModelStore },
        { defaultViewModelProviderFactory })

    //2.使用工具类导包方法简化写法 实现原理和上面一样
    //    implementation  'androidx.fragment:fragment-ktx:1.6.1'
    //    implementation  'androidx.activity:activity-ktx:1.6.1'
    val vm2: MyviewModel by viewModels<MyviewModel> { defaultViewModelProviderFactory }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.i("TAG", "---创建--onCreate")
        setContentView(R.layout.activity_main)

        //3.ViewModelProvider
        val vm3: MyviewModel = ViewModelProvider(
            viewModelStore,//这个对象只有在Activity创建之和才会有
            defaultViewModelProviderFactory
        ).get(MyviewModel::class.java)

        //4 java 中方法  implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0-alpha03'
//         myViewModle = ViewModelProviders.of(this).get(MyViewModle.class);

 //val mviewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(this.application))[MyviewModelTwo::class.java]
       // mviewModel.getName()

        //输出结果
        Log.i("MainActivity", "vm1.getName ${vm1.getName()}")
        Log.i("MainActivity", "vm2.getName ${vm2.getName()}")
        Log.i("MainActivity", "vm3.getName ${vm3.getName()}")
    }

    override fun onStart() {
        super.onStart()
        Log.i("TAG", "---开始--onStart")
    }

    override fun onResume() {
        super.onResume()
        Log.i("TAG", "---运行--onResume")
    }

    override fun onPause() {
        super.onPause()
        Log.i("TAG", "---暂停--onPause")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i("TAG", "---销毁--onDestroy")
    }

    override fun onStop() {
        super.onStop()
        Log.i("TAG", "---停止--onStop")
    }

    override fun onRestart() {
        super.onRestart()
        Log.i("TAG", "---重新启动--onRestart")
    }


}

Log 日志:

Kotlin 复制代码
打开启动: 
 ---创建--onCreate
: MyviewModel ViewModel 初始化
vm1.getName ---MyviewModel getName()方法-1704437476931
vm2.getName ---MyviewModel getName()方法-1704437476931
vm3.getName ---MyviewModel getName()方法-1704437476931
---开始--onStart
---运行--onResume


home 键退出:
---暂停--onPause
---停止--onStop


重新打开:
---重新启动--onRestart
---开始--onStart
 ---运行--onResume


退出应用:
---暂停--onPause
---停止--onStop
: MyviewModel onCleared 销毁方法
---销毁--onDestroy
相关推荐
用户2018792831678 分钟前
Binder 同应用内(本地)通信是否存在 1MB 大小限制?
android
一条上岸小咸鱼23 分钟前
Kotlin 基本数据类型(四):String
android·前端·kotlin
INS_KF23 分钟前
【C++知识杂记2】free和delete区别
c++·笔记·学习
Easocen1 小时前
Mybatis学习笔记(五)
笔记·学习·mybatis
Onion_991 小时前
学习下Github上的Android CICD吧
android·github
来来走走2 小时前
Flutter Form组件的基本使用
android·flutter
顾林海2 小时前
Android MMKV 深度解析:原理、实践与源码剖析
android·面试·源码阅读
丑小鸭是白天鹅3 小时前
嵌入式C语言学习笔记之枚举、联合体
c语言·笔记·学习
雨白3 小时前
TCP/IP 核心概念详解:从网络分层到连接管理
android
Wgllss4 小时前
雷电雨效果:Kotlin+Compose+协程+Flow 实现天气UI
android·架构·android jetpack