開發(fā)環(huán)境
- IDE:Android Studio 2.1
- Gradle版本:com.android.tools.build:gradle:2.1.2
- java版本: 1.8
實(shí)現(xiàn)方式
自定義屬性 (Custom Setters)
布局文件:
<layout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android" >
<data>
<variable name="str" type="String"/>
<variable name="btnTxt" type="String"/>
</data>
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{"CLICK",default=dft_txt}'
app:click="@{str}"
/>
</RelativeLayout>
</layout>
java代碼:
@BindingAdapter("bind:click")
public static void buttonClick(View view, String data){
view.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view){
//......
}
});
}
DataBinding框架會自動尋找使用了@BindingAdapter注解的方法并找到與之匹配的,如果需要傳入多個(gè)參數(shù)下發(fā)如下:
<variable name="str" type="String"/>
<variable name="data " type="String"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{"CLICK",default=dft_txt}'
app:click="@{str}"
app:data="@{data}"
/>
@BindingAdapter({"bind:click","bind:data"})
public static void buttonClick(View view, String data,String data2){
view.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view){
//......
}
});
}
事件處理 (Event Handling)
布局文件:
<layout>
<data>
<variable name="btnTxt" type="String"/>
<variable
name="presenter"
type="com.samples.Activity.example.Presenter"/>
</data>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{"CLICK",default=dft_txt}'
android:onClick="@{(view) -> presenter.click(view,btnTxt)}"
android:id="@+id/button2" />
</RelativeLayout>
</layout>
也可以寫做
android:onClick="@{() -> presenter.click(btnTxt)}"
java代碼:
public class Presenter{
public void click(View view,String str){
Toast.makeText(DataBindingListenerActivity.this,"CLICKED"+str,Toast.LENGTH_LONG).show();
}
public void click(String str){
Toast.makeText(DataBindingListenerActivity.this,"CLICKED",Toast.LENGTH_LONG).show();
}
}
可以看到上面代碼用到了Lambda表達(dá)式,這就是用java1.8的原因.但是通過觀察build文件夾下生成的XXXbinding.java中并沒有使用Lambde表達(dá)式.這里xml中寫的并不算java中的Lambda,這就很奇怪了
本文建立在已經(jīng)對DataBinding有所了解的基礎(chǔ)上介紹的.更多詳細(xì)介紹官方文檔:https://developer.android.com/topic/libraries/data-binding/index.html#event_handling