从ViewModel中启用/禁用登录按钮



家伙我有登录页面2 editText字段(用户名,密码)和1个按钮(提交)

我想启用提交按钮时,写的东西都是editText.

创建了两个LiveData变量

val _userName = MutableLiveData<String>()
val userName: LiveData<String>
get() = _userName
val _password = MutableLiveData<String>()
val password: LiveData<String>
get() = _password

这是我的提交按钮在xml

<com.google.android.material.button.MaterialButton
android:id="@+id/uSubmit"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="80dp"
android:text="@string/log_in_button_text"
android:enabled="@{authViewModel.isSubmitButtonEnabled()}"
android:onClick="@{_ -> authViewModel.uUserLogin()}"
android:clickable="false"
app:layout_constraintEnd_toEndOf="@+id/passwordInputLayout"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="@+id/passwordInputLayout"
app:layout_constraintTop_toBottomOf="@+id/passwordInputLayout" />

我试图在viewModel中编写此代码,以便在userName字段

中写入时启用按钮
var isSubmitButtonEnabled = (Transformations.map(userName) {
it.isNotEmpty()
})

,这很好。现在我想启用按钮时,在用户名和密码变量是写的东西。我该怎么做呢?

不需要使用viewmodel来实现这一点。你可以简单地只使用xml+databinding来获得正确的

<com.google.android.material.button.MaterialButton
android:id="@+id/uSubmit"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="@string/log_in_button_text"
android:enabled="@{!PASSWORD_EDITTEXT_ID_IN_CAMEL_CASE.text.toString().isEmpty() &amp;& !USERNAME_EDITTEXT_ID_IN_CAMEL_CASE.text.toString().isEmpty()}"
... />

最新更新