Kotlin: Jetpack — ViewModel简单应用

ViewModel 概览   Android Jetpack 的一部分。

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

1.导包:

    //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()

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

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 日志:

打开启动: 
 ---创建--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

猜你喜欢

转载自blog.csdn.net/jiayou2020527/article/details/135410146