android - 使用数据绑定(bind)库验证 edittext 输入

标签 android kotlin android-databinding android-mvvm

我正在使用数据绑定(bind)库。我有一个布局,其中包含一些用于获取基本用户输入(如姓名、电子邮件、密码等)的编辑文本。我想在单击按钮时在 View 模型中验证这些输入。我有点困惑如何在 View 模型内单击按钮时访问edittext输入。

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="ViewModel"
        type="me.example.model.LoginViewModel"/>

 <EditText
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="13sp" />

  <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:text="Submit"
     android:onClick="@{() -> ViewModel.onSubmitClick()}"/>

</layout>
这是 View 模型中的按钮单击方法
 fun onSubmitClick(){
    Log.e("Clicked ", "True")

    }

}

最佳答案

您可以在 Button 的绑定(bind)表达式中引用 EditText:

 android:onClick="@{() -> ViewModel.onSubmitClick(name.getText().toString())}"
一个警告是蛇肠衣在这样做时变成 Camel 肠衣,所以如果你的 View 的android:idname_edit_text ,您将使用 nameEditText.getText()在绑定(bind)表达式中。
单击 Button 将在 ViewModel 中调用此方法:
fun onSubmitClick(editTextString: String) {
    Log.d("LOG", editTextString)
}

关于android - 使用数据绑定(bind)库验证 edittext 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63652509/

相关文章:

kotlin - 多个distinctBy不会给出一致的结果

android - 为数据绑定(bind)创建自定义绑定(bind)适配器

android - 不应该为 RecyclerView 项目 View 使用数据绑定(bind)吗?

android - 如何移动 Android Studio 的菜单栏

android - "CheckDuplicateJavaLibraries"任务意外失败

kotlin - 未找到生成的类

android - 在 Android 中使用 Glide 和 Kotlin 在 ScrollView/RecyclerView 中显示 n 个图像

android - 我应该如何在 Android 的 viewModel 中获取 Resources(R.string)(MVVM 和数据绑定(bind))

android - react 原生 : A problem occurred evaluating project ':app' when trying to run on Android

javascript - Fit Screen Android WebApp(避免水平滚动)