简体   繁体   English

如何将 editText 值传递给 viewModel 和 Livedata (Kotlin)

[英]How to pass editText value to viewModel and Livedata (Kotlin)

I'm studying Android + Kotlin and make a simple example to understand LiveData + ViewModel.我正在学习 Android + Kotlin 并通过一个简单的例子来理解 LiveData + ViewModel。 It's very simple: I have one root activity and two fragments.这很简单:我有一个根活动和两个片段。 FragmentOne has two EditTexts. FragmentOne 有两个 EditText。 That values are summed and I need to pass the result to a ViewModel.这些值被求和,我需要将结果传递给 ViewModel。 Then I use observe in both root activity and FragmentTwo to see the changed data.然后我在根活动和 FragmentTwo 中使用观察来查看更改的数据。

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<Button>(R.id.sendToModel)
     btn?.setOnClickListener({
         val field1 = n1.text.toString().toInt()
         val field2 = n2.text.toString().toInt()
         resultSum = field1 + field2
         model.update()
     })
     return view
  }
}

viewModel视图模型

class MyViewModel: ViewModel() {
   private val fragment by lazy {FragmentOne()}
   private var _result = MutableLiveData<Int>().apply { value = 0 }
   val result: LiveData<Int>
      get() = _result

   fun update(){
       _result.value = fragment.resultSum
   }
}

Observer root activity观察根活动

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

I checked var resultSum (Log) and It hold Int value from sum.我检查了var resultSum (Log) 并保存了总和中的 Int 值。 The observer is working too (if I instantiate result.value inside ViewModel, the value is observable to activity and fragment)观察者也在工作(如果我在 ViewModel 中实例化result.value ,则活动和片段可以观察到该值)

I appreciate any help.我很感激任何帮助。

ViewModel should not have any reference to Android.* libraries. ViewModel 不应引用 Android.* 库。 So you having a reference to FragmentOne is a bad practice.所以你引用 FragmentOne 是一种不好的做法。

A cleaner approach is to change the update() function to accept a String -更简洁的方法是更改update()函数以接受字符串 -

 fun update(result: String){
        _result.value = result
    }

And change your FragmentOne code to say -并更改您的 FragmentOne 代码说-

btn?.setOnClickListener({
    val field1 = n1.text.toString().toInt()
    val field2 = n2.text.toString().toInt()
    resultSum = field1 + field2
    model.update(resultSum)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 LiveData 在 ViewModel 中启动 Kotlin 协程 - How to start Kotlin Coroutine in ViewModel with LiveData 如何使用 Kotlin 从 EditText 获取 LiveData 值并将其显示在 TextView 中? MVVM - How To Get LiveData Value From EditText and Display It In A TextView Using Kotlin? MVVM Kotlin:如何在 viewModel 中观察一次 liveData ? 使用 ObserveForever() 和 removeObserver() - Kotlin: How to Observe Once a liveData in a viewModel ? Using ObserveForever() and removeObserver() 如何让 EditText 在不使用数据绑定的情况下观察 ViewModel 的 LiveData 并将用户输入转发到 ViewModel - How to make EditText observe a ViewModel's LiveData and forward user input to the ViewModel without using data binding Viewmodel观察LiveData - 怎么样? - Viewmodel observing LiveData - how? 如何在 ViewModel 中观察 LiveData? - How to observe on LiveData in ViewModel? 在 Kotlin 中使用 ViewModel 和 LiveData 实现滑动删除 - Implementation of Swipe to Delete using ViewModel and LiveData in Kotlin 如何在 ViewModel 中为数据类参数 LiveData 设置初始化和设置值 - How to set initialize and set value to data class parameter LiveData in ViewModel 如何在 viewModel 中测试从存储库返回 LiveData 值的方法 - How to test a method in viewModel which returns LiveData value from repository 如何使用 kotlin 将 livedata 的结果作为 function 参数传递 - How to pass result of livedata as a function argument using kotlin
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM