【问题标题】:Adjust Textview according to variable in Kotlin根据Kotlin中的变量调整Textview
【发布时间】:2022-01-04 21:55:34
【问题描述】:

我正在使用 kotlin 在 Android Studio 中构建一个应用,

该应用程序是一个测验应用程序,最后会根据结果显示文本。

我想知道,将值(我猜是意图)从第一个活动移动到最后一个活动的最平滑方法是什么,并在途中对其进行调整。以及如何使用此值来调整结果活动上显示的字符串?

我正在考虑为所有结果创建字符串并将它们命名为 result100、result200、result300 等。然后有一个根据答案而变化的变量,例如:

buttonParty.setOnClickListener{    
            desNumber = 100
            val intent = Intent(this, ResultPageActivity::class.java)
            intent.putExtra("EXTRA_DES", desNumber)
            startActivity(intent)
        }

检索它:

val desNumber = intent.getIntExtra("EXTRA_DES", 100)

比上次活动:

resultText.setText = findViewById(R.string.result$desNumber)

但不幸的是,这似乎不起作用。

提前感谢您的帮助!

【问题讨论】:

  • 我建议您遵循“单一活动”架构,这样您就可以将 ViewModel 中的任何全局变量保留在您的活动范围内,并通过在各自的片段中执行 val activityModel by activityViewModels() 来读取它们Fragments。请参考 Android 团队 youtube.com/watch?v=2k8x8V77CrU 的此视频并查找“MVVM”和“Jetpack Navigation”。祝你好运!

标签: java android kotlin


【解决方案1】:

您可以使用名为 ViewModel 的东西来做到这一点

所以你会做这样的事情:

-在您的父活动(第一个)上,创建将保存您的数据的 ViewModel,以及将更改(或检索)该数据的函数:

class GameActivity : AppCompatActivity() {
 class GameData: ViewModel(){
        //Creates the variables that hold the data, with a type that allows them to change over time,
        //and to be "observed", but not be useful to this specific example, but this is what I usually use
        private val _Result1 : MutableLiveData<String> by lazy {
            MutableLiveData<String>().apply { value = "You got a Low Score" }
        }
        private val _Result2 : MutableLiveData<String> by lazy {
            MutableLiveData<String>().apply { value = "You got a High Score" }
        }

        //Publishes the values of the strings without letting them being altered directly
        val Result1 : LiveData<String>
            get() = _Result1
        val Result2 : LiveData<String>
            get() = _Result2
    }
}

-在要检索数据的活动上,执行以下操作:

    //Declare the variable that will give access to the variables
    private val dataModel : GameActivity.GameData by activityViewModels()

    //Acess the variables
    if(dataModel.Result1.value === "...")

虽然此答案显示了如何创建模型以将数据保存在一个活动中并在其他活动中访问,但我认为您的操作方式(保存不同的消息以显示)可能会以不同的方式做得更好。您不应该只是将“点”值保存在数据模型中,并使用条件来显示不同的消息吗? 您可以像使用上面的字符串一样保存此数据模型中的点,但在数据类型中使用“Int”而不是“String”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 2019-01-06
    • 1970-01-01
    相关资源
    最近更新 更多