如何在Android上为EditText数据绑定到onTextChanged? [英] How to databind to onTextChanged for an EditText on Android?

查看:558
本文介绍了如何在Android上为EditText数据绑定到onTextChanged?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Yitit Boyar和George Mount关于Android数据绑定的演讲中它们说明了绑定到TextWatcheronTextChanged是多么容易(在13:41).在一个按钮上.他们的幻灯片错了吗?首先,Button视图没有onTextChanged属性.它都没有setOnTextChanged方法. EditText都没有.但是它们都具有addTextChangedListener,它需要以TextWatcher作为输入.

In Yigit Boyar and George Mount's talk on Android Databinding they illustrate how easy it is to bind to TextWatcher's onTextChanged (at 13:41). On a Button. Are their slides wrong? First of all the Button View doesn't have an onTextChanged property. It neither has a setOnTextChanged method. Neither does EditText. But they both have addTextChangedListener which takes a TextWatcher as input.

那么他们在说什么?他们是如何做到的呢?他们的示例代码无法编译,但是会出现此错误:

So what are they talking about? How do they do it? Their example code does not compile, but gives this error:

Error:(17) No resource identifier found for attribute 'onTextChanged' in package 'android'

如何使用Android数据绑定框架绑定到任何视图(尤其是EditText)上的文本更改事件"?

How do I bind to a "Text Changed Event" on any View, or EditText in particular, with the Android Databinding framework?

推荐答案

实际上,它是开箱即用的.我认为我的错误是使用了旧版本的数据绑定框架.使用最新的过程是这样的:

Actually it works out of the box. I think my mistake was using an old version of the data binding framework. Using the latest, this is the procedure:

查看:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/username"
    android:text="Enter username:"
    android:onTextChanged="@{data.onTextChanged}" />

型号:

public void onTextChanged(CharSequence s, int start, int before, int count) {
    Log.w("tag", "onTextChanged " + s);
}

还请确保已将模型分配给 DataBinding

例如在您的活动中

lateinit var activityMainDataBinding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    activityMainDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) 
    val dataViewModel = ViewModelProvider(this).get(DataViewModel::class.java)
    activityMainDataBinding.dataModel = dataViewModel
}

确保您引用的是Gradle构建工具v1.5.0或更高版本,并在build.gradle中启用了android.dataBinding.enabled true数据绑定.

Make sure you are referncing gradle build tools v1.5.0 or higher and have enabled databinding with android.dataBinding.enabled true in your build.gradle.

编辑:正在运行的演示项目这里. 视图.

edit: Functioning demo project here. view. model.

这篇关于如何在Android上为EditText数据绑定到onTextChanged?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆