I have an xml with multiple TextInputLayouts. One of them goes as follows:
<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>
In my viewmodel I have text change listener implemented as follows:
fun onTextChanged(text: CharSequence){
Log.i("LoginViewModel", "username = "+text)
}
What I want to do is something like this:
fun onTextChanged(text: CharSequence, view: View){
when(view.id){
R.id.editText1 -> doSomething1()
R.id.editText2 -> doSomething2()
}
Is it possible to pass view/id/reference of the view that triggered the method, when databinding is used to call methods?
Yes, you can pass your views in databinding, simply create a method with View
a parameter in the view model:
fun onTextChanged(text: CharSequence, view: View){
when(view.id) {
R.id.editText1 -> doSomething1()
R.id.editText2 -> doSomething2()
}
}
Then pass the view's id to the method in XML layout:
<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"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With