找不到上下文时如何在 Kotlin 代码中获取 XML 的资源?

How to get XML's resources in Kotlin code when cannot find context?

按钮的文本切换 OK/Canel 取决于它的 onClickListener()

“确定”和“取消”在代码和XML中都定义了,如何在一个地方定义它们?

我尝试使用 btnText.value = application.resources.getString(R.string.cancel)

但是,应用程序只能在viewModel.class中找到init{}

viewModel.class中:

class xxxViewModel(application: Application, ...

    val btnText = MutableLiveData<String>()

    fun funForListener(){
        if (condition) btnText.value ="OK"
        else btnText.value ="Cancel"

        // error, cannot find application
        btnText.value = application.resources.getString(R.string.cancel)
    }
     
    init{
        // no error
        btnText.value = application.resources.getString(R.string.cancel)
    }

在res/strings.xml:

<string name="cancel">Cancel</string>
<string name="ok">OK</string>

您的主构造函数没有声明属性,而只是接收参数。这些只能在 init 块中使用。使用

class xxxViewModel(val application: Application, ...) 

而不是在 xxxViewModel class

中定义一个 application 属性

https://kotlinlang.org/docs/classes.html#constructors