一怀跛,介紹
谷歌去年就推出databinding框架脊僚,由于之前一直用的是butterknief相叁,所以一直沒(méi)有去學(xué)習(xí),最近一直聽(tīng)朋友在群里面說(shuō)該框架是多么的好用,所以忍不住趁著周日學(xué)習(xí)了一下增淹。
二椿访,初步配置
databinding的使用非常簡(jiǎn)單,因?yàn)槭枪雀柰瞥雎侨螅灾恍枰谠赽uild.gradle中配置
<pre>
android {
dataBinding {
enabled =true} }
</pre>
前提是在androidStudio1.5版本以上
三成玫,代碼演示
首先列舉一個(gè)簡(jiǎn)單的場(chǎng)景,在界面顯示姓名和年齡拳喻,通過(guò)界面中的點(diǎn)擊按鈕時(shí)改變姓名
xml布局
<pre>
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="user"
type="com.hgsoft.cardutils.activity.UserBean"></variable>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.name}"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.age}"/>
<Button
android:id="@+id/btn"
android:text="點(diǎn)擊"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
</pre>
首先可以看出哭当,跟普通布局的差別就是根節(jié)點(diǎn)變?yōu)?lt;layout>,需要在data節(jié)點(diǎn)中聲明variable屬性,就是對(duì)應(yīng)的你自定義的實(shí)體類(lèi)舞蔽,name為自己定義的別名荣病,type中包名一定要寫(xiě)全码撰,接下來(lái)就是在代碼中的體現(xiàn)了渗柿。
<pre>
public class DataActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityDataBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_data);
UserBean userBean=new UserBean("wangbin","24");
binding.setUser(userBean);
}
}
</pre>
在oncreate方法里面用DataBindingUtil.setContentView代替setcontentview方法,然后調(diào)用binding.setuser(user就是在布局中聲明的別名)脖岛,這樣就把值賦給了activity的對(duì)應(yīng)控件朵栖。
給按鈕添加點(diǎn)擊事件
<pre>
binding.btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
</pre>
四,優(yōu)缺點(diǎn)
由于學(xué)習(xí)時(shí)間比較簡(jiǎn)單柴梆,上面介紹只是很簡(jiǎn)單的使用陨溅,但是可以很直觀的看出該框架比較簡(jiǎn)潔,減少了findviewbyid的代碼绍在,當(dāng)然他肯定還有很多強(qiáng)大的地方门扇,需要后面來(lái)深入學(xué)習(xí),自我感覺(jué)針對(duì)一些簡(jiǎn)單的布局使用起來(lái)還是很方便偿渡,可是復(fù)雜的布局可能就有點(diǎn)吃力了臼寄,并且androidstudio支持并不是太好,以后空閑時(shí)間再深入學(xué)習(xí)一下溜宽,以便對(duì)該框架有一個(gè)全面的認(rèn)識(shí)吉拳。