jetpack-DataBinding onClick 的几种点
2020-08-16 本文已影响0人
seekting
DataBinding onClick 的几种点击方式
1.@{click}
//xml:
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{click}"
/>
//ViewModel:
public void click(View view){
}
2.不带参数:@{() -> viewModel.click()}
//xml:
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{() -> viewModel.click()}"
/>
//ViewModel:
public void click(){
}
3.@{viewModel::click}
//xml:
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{viewModel::click}"
/>
//ViewModel:
public void click(View view){
}
tip: 如果是在其它类中设置点击方法,如 EventHandlers.java, 其实与上面一致
//xml:
<variable
name="handler"
type="com.xx.xxx.EventHandlers" />
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{handler::click}" />
// UI类:绑定handler,如绑定ViewModel那样
EventHandlers handler = new EventHandlers();
binding.setHandler(handler);
// EventHandlers 执行click事件
public void click(View view){
//do
}
4.带参数:@{() -> viewModel.click(obj.id)}
//xml:
<variable
name="viewModel"
type="com.xx.xxx.ViewModel" />
<variable
name="obj"
type="com.xx.xxx.User" />
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{() -> viewModel.click(obj.id)}"
/>
//ViewModel:
public void click(long id){
//do
}
5.ObservableField<OnClickListener>
//xml:
<variable
name="iconView"
type="com.xxxxx.IconView" />
<RelativeLayout
android:id="@+id/rl_icon_view"
android:layout_width="match_parent"
android:layout_height="55dp"
android:onClick="@{iconView.clickListener}"
>
//IconView:
public final ObservableField<OnClickListener> clickListener=new ObservableField<>();
//xml所在的Activity类:
binding.iconView.clickListener.set(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"iconView",Toast.LENGTH_SHORT).show();
}
});
6.带参数
android:onClick="@{()->loadingModel.chooseLang(2)}"
public void chooseLang(int language) {
LogUtil.i(TAG, "language=" + language);
}
7. 带view的参数
//xml:
<variable
name="listener"
type="test.carrie.todomvvmtest.ui.OnTaskItemListener"/>
android:onClick="@{(view)->listener.onCheckBoxClick(obj,view)}"
//adapter:
public void onCheckBoxClick(ToDo entity, View v) {
}