问题描述
在 Yigit 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);
}
还要确保您已将 model 分配到 DataBinding
Make also sure that you have assigned model into 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!