Databinding 的几种 click 方式
2019-04-10 本文已影响0人
caitiancai
Databinding 的几种 click 方式
前提:
有一个 ViewModel 类,有一个 xml,xml 绑定了 ViewModel .
1. @{click}
//xml:
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{click}"
/>
//ViewModel:
public void click(View view){
//do
}
2. 不带参数:@{() -> viewModel.click()}
//xml:
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{() -> viewModel.click()}"
/>
//ViewModel:
public void click(){
//do
}
3. @{viewModel::click}
/xml:
<Button
android:layout_width="match_parent"
android:layout_height="48dp"
android:onClick="@{viewModel::click}"
/>
/ViewModel:
public void click(View view){
//do
}
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}" />
//类:绑定handler,如同绑定ViewModel那样
EventHandlers handler = new EventHandlers();
binding.setHandler(handler);
//EventHandlers
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. 自定义View中
/xml:
<variable
name="iconView"
type="com.adsale.ChinaPlas.ui.view.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);
}