谷歌的databinding非常好用,但是前提你得熟悉各種用法,否則坑很多,很容易從入門到放棄。
後來在實際開發中,碰到很多問題,經過自己的探索和修改,逐漸提升了對databinding的熟練度,下面我會額外講解其常見用法
強烈建議封裝在自己的ViewModel中再使用,既方便管理,也符合規範
1.常見的TextView的文字加載非常簡單
如果需要直接拼接一些文字,則需要特殊的單引號
android:text="@{bean.text}"
android:text="@{bean.text+ `元`}"
2.圖片加載
圖片加載需要使用一個特殊的註解BindingAdapter
詳細用法請參考
Databinding中ImageView的用法和坑(Java和Kotlin),附帶Glide用法
public class BaseViewModel {
@BindingAdapter({"app:imgRes"})
public static void setImageView(ImageView imageView, int res) {
imageView.setImageResource(res);
}
@BindingAdapter({"app:imgUrl"})
public static void setImageView(ImageView imageView, String url) {
if(TextUtils.isEmpty(url)){
return;
}
Glide.with(imageView.getContext()).load(url).into(imageView);
}
public int switchStatusImage() {
int imgRes = 0;
switch (需要判斷的值) {
case 0:
imgRes = R.drawable.icon_******;
break;
case 1:
imgRes = R.drawable.icon_******;
break;
case 3:
imgRes = R.drawable.icon_******;
break;
default:
break;
}
return imgRes;
}
}
其中viewModel.switchStatusImage() 只是封裝而已,其實就是一個圖片地址的引用
app:imgRes="@{viewModel.switchStatusImage()}"
3.visibility
有時候有一些控件需要在特定的條件下隱藏或者顯示,那該怎麼辦呢?
注意,如果不進行ViewModel的封裝,而是直接使用,需要在xml當中導包
<import type="android.text.TextUtils"/>
<import type="android.view.View"/>
****
*****
****
android:visibility="@{TextUtils.isEmpty(bean.status) ? View.VISIBLE : View.GONE}"
4.顏色 textColor
<import type="android.text.TextUtils"/>
<import type="androidx.core.content.ContextCompat"/>
<import type="com.你自己項目的包名.R"/>
****
****
****
android:textColor="@{TextUtils.isEmpty(bean.status) ? ContextCompat.getColor(context,R.color.green_61A71F):ContextCompat.getColor(context,R.color.black_333333)}"
5.特殊字符
databinding 如果在設置text屬性時,一些特殊字符是無法直接使用的,在編譯的時候回報錯,比如空格、“|”等等
這個時候需要使用string的引用來完成
android:text="@{bean.house_type +@string/separator+ bean.space +`m²`}"
不過後來實際開發發現,空格的引用也是無效的,如果封裝在ViewModel中使用則跟普通的text一樣
比如
public String description() {
return " | " + mRoomsBean.getSpace() + "m²";
}
***
***
***
android:text="@{viewModel.description()}"
6.點擊事件
/**
* 跳轉到撥號界面,同時傳遞電話號碼
*/
public void skipToCallActivity(Context context, String phoneNumber) {
Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
context.startActivity(dialIntent);
}
***
***
***
android:onClick="@{() -> viewModel.skipToCallActivity(context,bean.phone)}"
ps:如果封裝成ViewModel,則需要額外導包
注意,所有的方法都是public 才能使用
<data>
<variable
name="bean"
type="com.*******.Bean"/>
<variable
name="viewModel"
type="com.*******.ViewModel"/>
</data>
binding.setBean(bean);
binding.setViewModel(new ViewModel(bean));