kotlin 初始化变量

class PlaylistViewNewModel (var playlist: Playlist?) : ViewModel() {
    var limit = 100
    private val name  by lazy {
        //lazy 只会执行一次
        playlist?.id
    }

    //重写get方法  每次使用都是调用get(方法)
    private val playlistId: String
    get() = playlist?.id ?: ""



}


使用

初始化
mPlaylistVM = PlaylistViewNewModel(null)

设置变量

PlaylistVM?.playlist = playlist



ViewModel 初始化

fragment

private val mMyPlaylistVM by lazy {
        ViewModelProvider(this)[MyPlaylistViewModel::class.java]
    }

   

父fragment内共用

    private val mMyPlaylistVM1 by lazy {
        ViewModelProvider(requireParentFragment())[MyPlaylistViewModel::class.java]
    }


activity内共用

    private val mPlayVM by lazy {
        ViewModelProvider(requireActivity())[PlayViewModel::class.java]
    }

你可能感兴趣的:(kotlin,开发语言,android)