有一个 ViewModel 类,有一个 xml,xml 绑定了 ViewModel .
1. 不带参数:@{() -> viewModel.click()}
<!--xml:-->
...
<data>
<variable
name="vm"
type="com.xxx.xxx.MainViewModel" />
</data>
...
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{() -> vm.click()}"
...
/>
//ViewModel:
public void click(){
}
2. @{viewModel::click}
<!--xml:-->
...
<data>
<variable
name="vm"
type="com.xxx.xxx.MainViewModel" />
</data>
...
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{vm::click}"
/>
...
//ViewModel:
public void click(View view){
}
3. 带参数:@{() -> viewModel.click(obj.id)}
<!--xml:-->
<variable
name="vm"
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="@{() -> vm.click(obj.id)}"
/>
//ViewModel:
public void click(long id){
//do }
4.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();
}
});
5. 带view的参数
<!--xml:-->
<variable
name="listener"
type="test.carrie.todomvvmtest.ui.OnTaskItemListener"/>
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{(view)->listener.onCheckBoxClick(view,obj)}"
/>
//adapter:
public void onCheckBoxClick(View v,ToDo entity,) {
}
学习备忘 仅供参考