传递数据绑定方法参考中的视图ID或参考

我有一个带有多个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>

在我的视图模型中,我实现了文本更改侦听器,如下所示:

    fun onTextChanged(text: CharSequence){
    Log.i("Loginviewmodel", "username = "+text)
}

我想做的是这样的:

    fun onTextChanged(text: CharSequence, view: View){
    when(view.id){
        R.id.editText1 -> doSomething1()
        R.id.editText2 -> doSomething2()
}

当使用数据绑定调用方法时,是否可以传递触发该方法的视图的view / id / reference?

解决方法:

是的,您可以在数据绑定中传递视图,只需在视图模型中使用View参数创建方法

fun onTextChanged(text: CharSequence, view: View){
    when(view.id) {
        R.id.editText1 -> doSomething1()
        R.id.editText2 -> doSomething2()
    }
}

然后将视图的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"/>

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...