我正在研究Android Kotlin并做一个简单的例子来展示LiveData ViewModel.这很简单:我有一个根活动和两个片段. FragmentOne有两个editText.这些值相加,我需要将结果传递给ViewModel.然后,我在根活动和FragmentTwo中使用observe来查看更改的数据.
FragmentOne
class FragmentOne: Fragment() {
private val model by lazy { ViewModelProviders.of(activity).get(MyViewModel::class.java) }
var resultSum:Int = 0
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater?.inflate(R.layout.fragment_one,container,false)
val btn = view?.findViewById(R.id.sendToModel)
btn?.setOnClickListener({
val field1 = n1.text.toString().toInt()
val field2 = n2.text.toString().toInt()
resultSum = field1 + field2
model.update()
})
return view
}
}
视图模型
class MyViewModel: ViewModel() {
private val fragment by lazy {FragmentOne()}
private var _result = MutableLiveData().apply { value = 0 }
val result: LiveData
get() = _result
fun update(){
_result.value = fragment.resultSum
}
}
观察者根活动
private val resultModel by lazy {ViewModelProviders.of(this).get(MyViewModel::class.java)}
resultModel.result.observe(this, Observer { result -> resultTxt.text = result.toString()})
Observer FragmentTwo
private val resultModel by lazy {ViewModelProviders.of(activity).get(MyViewModel::class.java)}
resultModel.result.observe(this, Observer { result -> resultTxt.text = result.toString()})
我检查了var resultSum(Log)并且它保存了来自sum的Int值.观察者也在工作(如果我在ViewModel中实例化result.value,则值可以观察到活动和片段)
我感谢任何帮助.