android - 如何使用数据绑定(bind)从 xml 调用 Edittext onEditorAction

标签 android data-binding

如下面的代码

<data>
    <variable
      name="listener"
      type="android.view.View.OnClickListener" />
</data>


<TextView android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android: text="@ {user.firstName}"
     android:onClick="@{listener::onClick}"/>

我想从XML调用editorAction,可以通过xml来执行它吗?

最佳答案

1.创建接口(interface)

interface CustomOnEditorActionListener {
    fun onEditorAction()
}

2.BindingAdapter

@BindingAdapter("app:customOnEditorActionListener")
fun setCustomOnEditorActionListener(view: TextView, listener: CustomOnEditorActionListener?) {
    if (listener == null) {
        view.setOnEditorActionListener(null)
    } else {
        view.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                listener.onEditorAction()
                return false
            }
        })
    }
}

3.XML 格式。 viewModel实现接口(interface)CustomOnEditorActionListener

    ...
<variable
name="viewModel"
type="nl.login.LoginViewModel" />

    ...
<EditText
android:id="@+id/password_edit"
app:customOnEditorActionListener="@{viewModel}"
    ...

关于android - 如何使用数据绑定(bind)从 xml 调用 Edittext onEditorAction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51648366/

相关文章:

c# - DataGridView 使用 DataSourceNullValue : enter either nothing, 或 nullValue

c# - 如何绑定(bind)网格行高?

c# - 是否有更简洁的方法将属性绑定(bind)到所有者的 DataContext?

android - 布局中 ImageView 的 ANTI_ALIAS_FLAG?

android - hive 应用,LocalBroadcastManager

android - 在平板电脑的 Android 应用程序中获取外部存储路径

c# - 将 WPF ComboBox 绑定(bind)到自定义列表

android - 在 Dart/Flutter 中传递返回对象的函数不起作用

安卓 : Build a video

c# - 当集合为空时,UWP XAML 抛出未处理的异常