用 Kotlin 编写的 BMI ViewModel 计算器 [英] BMI ViewModel Calculator Written in Kotlin

查看:28
本文介绍了用 Kotlin 编写的 BMI ViewModel 计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试更新我的基本 Kotlin 代码,该代码根据用户的输入计算用户 BMI.我已经通过developer.android codelab实践了,还是搞不定.

Hello I am trying to update my basic Kotlin code that calculates a users BMI based on their input. I have already went through the developer.android codelab practice and still can't get it.

参考HERE是原始代码的链接计算所以它正在运行.

For reference HERE is the link to the original code that has been fixed with the correct calculation so it is running.

但现在我想使用 ViewModel,以便在配置更改时保存 UI 数据.但到目前为止,这就是我所拥有的,因为我知道 ViewModel 需要保存数据处理代码,而将 UI 数据留在常规类中是可以的,因为这只会处理 UI.

But now I want to use a ViewModel so the UI data is saved on configuration changes. But so far this is all I have since I know the ViewModel needs to hold the data processing code and leaving the UI data in the regular class is fine since this will deal with the UI only.

我不知道如何绑定所有数据或从 ViewModel 类正确访问它.如果有人可以帮忙.如果需要在此处添加我的原始代码以便于访问,我可以添加它,我只是不想将它们全部放在一起.请有人帮忙!

I don't know how to bind all the data or properly access it from the ViewModel class. If someone can help. If my original code needs to be added in here for easier access I can add it, I just didn't want to clump this all together. Please someone help!

'''

class bmiViewModel : ViewModel() {


val height = findViewById<EditText>(R.id.heightEditText)
val weight = findViewById<EditText>(R.id.weightEditText)

calcButton.setOnClickListener{
    var heightValue = 0.0
    var weightValue = 0.0
    if(height.text.toString().isNotEmpty()){
        heightValue = height.text.toString().toDouble()
    }
    if(weight.text.toString().isNotEmpty()){
        weightValue = weight.text.toString().toDouble()
    }

    if(weightValue > 0.0 && heightValue > 0.0){
        val bmiValue = String.format(" %.2f",
            (weightValue*703)/(heightValue*heightValue))
        
        val bmiDouble = bmiValue.toDouble()
        bmiInfo.text = "BMI is ${String.format("%.2f",bmiDouble)} you are " +
                       "${bmiResults((weightValue*703)/(heightValue*heightValue))}"
        bmiInfo.visibility = View.VISIBLE
    }
    else {
        Toast.makeText(
            this, "Please input Weight and Height Values greater than 0",
            Toast.LENGTH_LONG).show()
    }
}

// function to decide users BMI status
private fun bmiResults(bmi:Double):String{
    lateinit var answer: String
    if(bmi<18.5){
        answer="Underweight"
    } else if(bmi > 18.5 && bmi < 24.9) {
        answer="Normal"
    } else if(bmi > 24.9 && bmi < 30) {
        answer="Overweight"
    } else {
        answer="Obese"
    }
    return answer
}

}'''

推荐答案

你的 ViewModel 应该包含 2 个 MutableLiveData for height重量

Your ViewModel should contain 2 MutableLiveData for height and weight

您应该在 Fragment/Activity 中的 EditText 中添加 2 个 TextWatcher.

You should add 2 TextWatchers to your EditTexts inside your Fragment/Activity.

当在TextWatchers上调用afterTextChanged时,使用ViewModelMutableLiveData来设置值对应的数据.

When afterTextChanged is called on the TextWatchers, use the ViewModel's MutableLiveData to set the value of the corresponding data.

里面Fragment/Activity

   private val heightTextWatcher = object : TextWatcher {
      override fun afterTextChanged(s: Editable?) {
          viewModel.height.setValue(s.toString())
      }
      override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
      override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}


   private val weightTextWatcher = object : TextWatcher {
      override fun afterTextChanged(s: Editable?) {
          viewModel.weight.setValue(s.toString())
      }
      override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
      override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

内部 ViewModel

public var height: MutableLiveData<String> = MutableLiveData()
public var weight: MutableLiveData<String> = MutableLiveData()

fun onCalculate(){
    h = height.getValue()
    w = weight.getValue()
    //do math
}

Data 永远不会离开 ViewModelView 永远不会离开 Fragment/Activity

Data never leaves the ViewModel and the View never the leaves the Fragment/Activity

这篇关于用 Kotlin 编写的 BMI ViewModel 计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆