Issue
A button's text switchs OK/Canel depends on its onClickListener().
"OK" and "Cancel" was defined in both code and XML, how to define them at one place?
I tried to use btnText.value = application.resources.getString(R.string.cancel).
However, application can only be found inside init{} in viewModel.class.
In 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)
}
In res/strings.xml:
<string name="cancel">Cancel</string>
<string name="ok">OK</string>
Solution
Your primary constructor is not declaring properties, but just receiving parameters. These can only be used in the init block. Use
class xxxViewModel(val application: Application, ...)
instead to define an application property in the xxxViewModel class
https://kotlinlang.org/docs/classes.html#constructors
Answered By - derpirscher
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.