LiveData使用 navigation中activity fragment共享数据

使用LifeData需要添加依赖


    // ViewModel and LiveData
    implementation "android.arch.lifecycle:extensions:1.1.1"
    // alternatively, just ViewModel
    implementation "android.arch.lifecycle:viewmodel:1.1.1"
    // alternatively, just LiveData
    implementation "android.arch.lifecycle:livedata:1.1.1"

新建TestViewModel.kt

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class TestViewModel : ViewModel() {
    val currentName: MutableLiveData by lazy {
        MutableLiveData()
    }
}

navagation中fragment共享数据可以这样用

  // 注意,因为fragment要和activity共享数据,所以ViewModelProvider.of(  这里传入fragment依附的activity  )
 private val viewModel by lazy {
        ViewModelProviders.of(activity!!).get(TestViewModel::class.java)
    }



 //监听数据的改变
viewModel.currentName.observe(this, Observer {
            text.text = it
        })

如果要改变则直接setValue()

  change.setOnClickListener {
            viewModel.currentName.value = "已经改变了,现在是word"
        }

 

你可能感兴趣的