【问题标题】:DataBinding ViewModel get editText size and send it to new activityDataBinding ViewModel 获取 editText 大小并将其发送到新活动
【发布时间】:2020-11-20 08:08:02
【问题描述】:

您好,我从 MVVM 和 DataBinding 开始,所以我要做的是创建一个简单的 viewModel,其中包含一个字段让我们说名称,当用户单击按钮时,它会检查 editText 是否为空,如果是,请转到下一个活动(发送名称)。

我试过的是:

这是我的视图模型

class MainActivityViewModel : ViewModel() {

    private val _userName = MutableLiveData<String>()

    val username : LiveData<String> = _userName

    //Here I'd like to know if I have to use MutableLiveData<NameStatus> and this name status is Filled / Empty so my activity can react to it and show an error or something

    //And then when tapping the button it should check the edittext value and send it to next activity.


}

我还考虑在布局中添加类似按钮被禁用的内容,如果 editText 大小为 0,这可能是一个选项,但我想知道第一个选项,以便我可以处理状态并对说明 EditText 是填充还是空。

【问题讨论】:

  • 您遇到的困难究竟是什么?什么是 NameStatus?

标签: android kotlin mvvm data-binding


【解决方案1】:

你应该这样纠正你的代码:

class MainActivityViewModel : ViewModel() {

    private val _userName = MutableLiveData<String>()
    val username: LiveData<String>
        get() = _userName

    private val _isUserNameNotEmpty = MutableLiveData<Boolean>(false)
    val isButtonClickable: LiveData<Boolean>
        get() = _isUserNameNotEmpty

    

    fun usernameChanged(text: CharSequence?) {
        _userName.postValue(text.toString())
        _isUserNameNotEmpty.postValue(!text.isNullOrEmpty())
    }

}

这样,您将一个不可变变量暴露给外部,该变量返回您的私有变量_userName,您可以在您的活动中观察它。您需要让 viewModel 知道编辑文本中的更改,然后观察它是否在您的活动的onCreate() 中不为空,如下所示:

firstName.doOnTextChanged { text, start, count, after ->
     viewModel.usernameChanged(text)
}
viewModel.isButtonClickable.observe(this) {
     button.isClickable = it
     // you can make more actions here like changing the color of the button
}

但是,如果你想使用数据绑定 _userName 不能再是私有的,因为它需要通过编辑文本设置,所以你需要让你的 viewModel 像这样:

val userName = MutableLiveData<String>()

private val _isUserNameNotEmpty = MutableLiveData<Boolean>(false)
val isButtonClickable: LiveData<Boolean>
    get() = _isUserNameNotEmpty

没有更多功能了!!但是您丢失了封装。
现在确保在您的活动的onCreate() 中放置这一行以使实时数据与数据绑定一起工作:binding.lifecycleOwner = this,您不再需要以前的代码了。

现在您可以将它与您的 XML 绑定,例如在您的 textView 中的 android:text="@={ viewModel.username }" 和在您的按钮 xml 中的 android:clickable="@{ viewModel.isButtonClickable }"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-06
    • 2017-08-16
    • 2013-07-26
    • 2020-08-18
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    相关资源
    最近更新 更多