DataBinding onClick的七种点击方式
最近在学习DataBinding的使用,中间遇到了不少的坑,记录以下,帮助以后学习DataBinding的朋友。
有一个ViewModel类,有一个xml,xml绑定了ViewModel.
1.@{click}
//xml: //ViewModel: publicvoidclick(Viewview){ }
2.不带参数:@{()->viewModel.click()}
//xml: //ViewModel: publicvoidclick(){ }
3.@{viewModel::click}
//xml: //ViewModel: publicvoidclick(Viewview){ }
tip:如果是在其它类中设置点击方法,如EventHandlers.java,其实与上面一致
//xml://UI类:绑定handler,如绑定ViewModel那样 EventHandlershandler=newEventHandlers(); binding.setHandler(handler); //EventHandlers执行click事件 publicvoidclick(Viewview){ //do }
4.带参数:@{()->viewModel.click(obj.id)}
//xml://ViewModel: publicvoidclick(longid){ //do }
5.ObservableField
//xml://IconView: publicfinalObservableField clickListener=newObservableField<>(); //xml所在的Activity类: binding.iconView.clickListener.set(newView.OnClickListener(){ @Override publicvoidonClick(Viewv){ Toast.makeText(getApplicationContext(),"iconView",Toast.LENGTH_SHORT).show(); } });
6.带参数
android:onClick="@{()->loadingModel.chooseLang(2)}" publicvoidchooseLang(intlanguage){ LogUtil.i(TAG,"language="+language); }
7.带view的参数
//xml:android:onClick="@{(view)->listener.onCheckBoxClick(obj,view)}" //adapter: publicvoidonCheckBoxClick(ToDoentity,Viewv){ }