Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/189.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何将逻辑提取到viewModel?_Android_Kotlin_Android Mvvm - Fatal编程技术网

Android 如何将逻辑提取到viewModel?

Android 如何将逻辑提取到viewModel?,android,kotlin,android-mvvm,Android,Kotlin,Android Mvvm,在我的片段中,我有下一个代码: etAuthorName.doAfterTextChanged { viewModel.quoteAuthor.value = it?.toString() } viewModel.quoteAuthor.observe(this, Observer<String> { if (etAuthorName.text.toString() != it) { etAuthorName.setText(it) } })

在我的片段中,我有下一个代码:

etAuthorName.doAfterTextChanged {
    viewModel.quoteAuthor.value = it?.toString()
}

viewModel.quoteAuthor.observe(this, Observer<String> {
    if (etAuthorName.text.toString() != it) {
        etAuthorName.setText(it)
    }
})
etAuthorName.doAfterTextChanged{
viewModel.quoteAuthor.value=it?.toString()
}
viewModel.quoteAuthor.observe(此,观察者{
if(etAuthorName.text.toString()!=it){
etAuthorName.setText(it)
}
})

如何提取此逻辑:
if(etAuthorName.text.toString()!=it)
到我的viewModel?

在这种情况下,您可以使用数据绑定,请在此处了解更多信息:

编辑:您可以尝试以下操作:

在ViewModel类中:

@get:Bindable
var bindetAuthorName: String = ""
    set(value) {
        field = value
        notifyPropertyChanged(BR.bindetAuthorName)
    }
    get() = field

fun comparison(){
    if(bindetAuthorName != quoteAuthor){
        bindetAuthorName = quoteAuthor
    }
}
在xml edittext/textview中:

<Edittext
 .....
 android:text="@={viewModel.bindetAuthorName}"/>


每当quoteAuthor值更新时,可以调用comparison()。我希望这有帮助

您可以使用
转换。distinctUntilChanged
添加此内部视图模型,并在片段内部侦听 托尔

val authorDistinct = Transformations.distinctUntilChanged(quoteAuthor)

为了真正将逻辑移动到ViewModel

你可以换成这个

碎片

etAuthorName.doAfterTextChanged {
    viewModel.triggerQuoteAuthor(etAuthorName.text.toString(), it?.toString())
}

viewModel.quoteAuthor.observe(this, Observer<String> {
    etAuthorName.setText(it)
})

是的,我可以,但是我想在我的viewModel中提取这个逻辑,然后在使用数据绑定显示xml中没有任何逻辑的文本之后,您的viewModel中已经有了“quoteAuthor”,并且您可以有来自“etAuthorName”的文本在viewmodel中使用数据绑定,以便进行相同的比较;如果使用双向数据绑定,则可以在“etAuthorName”上设置文本直接从viewmodel。我不想在xml中进行比较我想在视图模型中有所有的逻辑,以便以后可以进行测试我说的是在viewmodel中进行比较。你需要在android项目中添加数据绑定:使用此链接
fun triggerQuoteAuthor(beforeText: String, afterText: String) {
   if (beforeText != afterText) {
      quoteAuthor.value = afterText
   }
}