Sar*_*Mjn 5 data-binding android kotlin
我有一个带有多个 TextInputLayouts 的 xml。其中之一如下:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textInputEmail"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginLeft="@dimen/default_margin"
android:layout_marginStart="@dimen/default_margin"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginEnd="@dimen/default_margin"
android:layout_marginRight="@dimen/default_margin"
android:layout_marginTop="@dimen/default_margin_half"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="@dimen/default_margin_half"
app:layout_constraintBottom_toBottomOf="parent">
<android.support.design.widget.TextInputEditText
android:id="@+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/email"
android:text="@={viewModel.username}"
android:onTextChanged="@{(text, start, before, count) -> viewModel.onTextChanged(text)}"
android:inputType="textEmailAddress"/>
</android.support.design.widget.TextInputLayout>
Run Code Online (Sandbox Code Playgroud)
在我的视图模型中,我实现了文本更改侦听器,如下所示:
fun onTextChanged(text: CharSequence){
Log.i("LoginViewModel", "username = "+text)
}
Run Code Online (Sandbox Code Playgroud)
我想做的是这样的:
fun onTextChanged(text: CharSequence, view: View){
when(view.id){
R.id.editText1 -> doSomething1()
R.id.editText2 -> doSomething2()
}
Run Code Online (Sandbox Code Playgroud)
当数据绑定用于调用方法时,是否可以传递触发方法的视图的视图/ID/引用?
是的,您可以在数据绑定中传递您的视图,只需View在视图模型中创建一个带有参数的方法:
fun onTextChanged(text: CharSequence, view: View){
when(view.id) {
R.id.editText1 -> doSomething1()
R.id.editText2 -> doSomething2()
}
}
Run Code Online (Sandbox Code Playgroud)
然后将视图的 id 传递给 XML 布局中的方法:
<android.support.design.widget.TextInputEditText
android:id="@+id/editTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/email"
android:text="@={viewModel.username}"
android:onTextChanged="@{(text, start, before, count) -> viewModel.onTextChanged(text, editTextEmail)}"
android:inputType="textEmailAddress"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2496 次 |
| 最近记录: |