[英]Android - <Include/> Data Binding
I've reading some examples and Android documentation, but my implementation isn't working 我正在阅读一些示例和Android文档,但我的实现不起作用
I've my activity and my viewmodel. 我有我的活动和我的视图模型。
Activity Layout 活动布局
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="viewmodel"
type="package.to.viewmodel"/>
</data>
<android.support.v4.widget.DrawerLayout>
<include
app:viewmodel="@{viewmodel}"/>
<!-- More Code -->
</android.support.v4.widget.DrawerLayout>
</layout>
Include Layout 包括布局
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="viewmodel"
type="package.to.viewmodel"/>
</data>
<android.support.design.widget.CoordinatorLayout>
<!-- More Code -->
<android.support.design.widget.FloatingActionButton
android:onClick="@{viewmodel.newButtonClickListener}"/>
</android.support.design.widget.CoordinatorLayout>
</layout>
ViewModel Code ViewModel代码
public class MainViewModelImpl implements MainViewModel {
private View.OnClickListener newButtonClickListener;
private View.OnClickListener newEventButtonClickListener;
private View.OnClickListener newAssignmentButtonClickListener;
private View.OnClickListener newContactButtonClickListener;
private View.OnClickListener newChatButtonClickListener;
//All the getters for the Listeners
}
So the code builds and runs without errors, but when I tap the button nothing happens, even though my listeners are correctly implemented. 所以代码构建和运行没有错误,但是当我点击按钮没有任何反应,即使我的听众正确实现。
Does anyone has an idea on why are the listeners not been triggered? 有没有人知道为什么听众没有被触发?
Update When I was debugging the application, I realize that the viewmodels in the include layout are null, even after the binding. 更新当我调试应用程序时,我意识到包含布局中的视图模型即使在绑定之后也是null。
I figured it out, I was doing the binding before inflating the view. 我想通了,我在给视图充气之前正在进行绑定。 So now it works. 所以现在它有效。
Thanks 谢谢
When you set the viewModel variable in the include you should use bind:viewmodel
instead of app:viewmodel
. 在include中设置viewModel变量时,应使用bind:viewmodel
而不是app:viewmodel
。
An example is available in the official documentation or in the demo project of my data binding talk. 官方文档或我的数据绑定谈话的演示项目中提供了一个示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.