如何在Android上为EditText数据绑定到onTextChanged? [英] How to databind to onTextChanged for an EditText on Android?
问题描述
在 Yitit Boyar和George Mount关于Android数据绑定的演讲中它们说明了绑定到TextWatcher
的onTextChanged
是多么容易(在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屋!