DataBinding使用詳解

配置

  • 在Module的build.gradle android模塊中添加如下配置:

    android {
     dataBinding {
        enabled = true
     }
    }
    

    ?

布局

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    
    <data>
    
    <!-- 數(shù)組集合類<import type="java.util.List"/>
         <import type="java.util.Map"/>-->
         
         <!-- 轉(zhuǎn)義 空格 &nbsp;     &#160;
        <   小于號(hào) &lt;   &#60;
        >   大于號(hào) &gt;   &#62;
        &   與號(hào)  &amp;   &#38;
        "   引號(hào)  &quot;  &#34;
        ‘   撇號(hào)  &apos;  &#39;
        ×   乘號(hào)  &times; &#215;
        ÷   除號(hào)  &divide;&#247;-->
         
         <!--<variable
                name="list"
                type="List&lt;String&gt;"/>
            <variable
                name="map"
                type="Map&lt;String,Object&gt;"/>-->
                
        <variable
            name="user"
            type="com.luuren.UserBean" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{user.name}" />

        <!--注意:這里age是int類型,必須轉(zhuǎn)化為String,否則會(huì)運(yùn)行時(shí)異常-->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{String.valueOf(user.age)}" />
    </LinearLayout>
</layout>

實(shí)體類

public class UserBean {
    private String name; //姓名
    private int age; //年齡

    public UserBean(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

使用

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_main);                  
        UserBean userBean = new UserBean ("Luuren", "26");
        binding.setUser(userBean );
    }
}

BindingAdapter注解設(shè)置自定義屬性

  • 使用此注解可以自定義控件的屬性,比如ImageView設(shè)置直接加載網(wǎng)絡(luò)圖片(當(dāng)然得借助Glide等網(wǎng)絡(luò)圖片加載框架的幫助,詳見代碼);
public class ImageHelper {

    /**
     * 1.加載圖片,無需手動(dòng)調(diào)用此方法
     * 2.使用@BindingAdapter注解設(shè)置自定義屬性的名稱,imageUrl就是屬性的名稱,
     * 當(dāng)ImageView中使用imageUrl屬性時(shí),會(huì)自動(dòng)調(diào)用loadImage方法,
     *
     * @param imageView ImageView
     * @param url       圖片地址
     */
    @BindingAdapter({"imageUrl"})
    public static void loadImage(ImageView imageView, String url) {
        Glide.with(imageView.getContext()).load(url)
                .placeholder(R.mipmap.fruit)
                .error(R.mipmap.fruit)
                .into(imageView);
    }
    /**
        多個(gè)屬性也是可以的
    */
    @BindingAdapter({"imageUrl", "placeHolder",error"})
    public static void loadImage(ImageView view, String url, Drawable holderDrawable,Drawable errorDrawable) {
         Glide.with(imageView.getContext())  
                    .load(url)  
                    .placeholder(holderDrawable)  
                    .error(errorDrawable)  
                    .into(imageView);
    }
}
  • 使用如下:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="com.luuren.bean.UserBean" />
        <variable
            name="user"
            type="UserBean" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:orientation="vertical">

        <!-- 當(dāng)imageUrl屬性存在時(shí),會(huì)自動(dòng)調(diào)用ImageHelper的loadImage方法 -->
        <ImageView
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:scaleType="centerCrop"
            app:imageUrl="@{user.picUrl}" />
    </LinearLayout>
</layout>

數(shù)據(jù)對(duì)象 (Data Objects)

  • 所謂的雙向綁定,其實(shí)就是類似于notifyDatasetChanged的操作,具體看代碼:
public class ContentBean extends BaseObservable {
    
    //BR 是編譯階段生成的一個(gè)類,功能與 R.java 類似,用 @Bindable 標(biāo)記過 getter 方法會(huì)在 BR 中生成一個(gè) entry,當(dāng)我們
    //通過代碼可以看出,當(dāng)數(shù)據(jù)發(fā)生變化時(shí)還是需要手動(dòng)發(fā)出通知。 通過調(diào)用notifyPropertyChanged(BR.firstName)來通知系統(tǒng) BR.firstName 這個(gè) entry 的數(shù)據(jù)已經(jīng)發(fā)生變化,需要更新 UI。

    private String content; //內(nèi)容

    public DoubleBindBean(String content) {
        this.content = content;
    }

    @Bindable
    public String getContent() {
        return content;
    }


    public void setContent(String content) {
        this.content = content;
        notifyPropertyChanged(BR.content); //通知系統(tǒng)數(shù)據(jù)源發(fā)生變化,刷新UI界面
    }
}
  • xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="doubleBindBean"
            type="com.luuren.bean.DoubleBindBean" />

        <variable
            name="onClickListener"
            type="android.view.View.OnClickListener" />

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="15dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{doubleBindBean.content}" />

        <Button
            android:id="@+id/change_content_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{onClickListener}"
            android:text="改變內(nèi)容了" />

    </LinearLayout>
</layout>
  • 這樣之后只需要操作數(shù)據(jù)就好了,不用關(guān)心UI的變化問題
  • ObservableFields : 如果想要省時(shí),或者數(shù)據(jù)類的字段很少的話,可以使用 ObservableField 以及它的派生 ObservableBoolean、 ObservableByte ObservableChar、ObservableShort、ObservableInt、ObservableLong、ObservableFloat、ObservableDouble、 ObservableParcelable 等。
public class ContentBean {
    //變量需要為public
    public final ObservableField<String> username = new ObservableField<>();
}
  • Observable Collections: 除了支持ObservableField,ObservableBoolean,ObservableInt等基礎(chǔ)變量類型以外,當(dāng)然也支持集合框架拉,比如:ObservableArrayMap,ObservableArrayList。使用和普通的Map、List基本相同
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="list"
            type="android.databinding.ObservableArrayList&lt;String&gt;" />

        <variable
            name="map"
            type="android.databinding.ObservableArrayMap&lt;String,Object&gt;" />

        <variable
            name="onClickListener"
            type="android.view.View.OnClickListener" />

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="15dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{list[0]}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text='@{map["key0"]}' />

        <Button
            android:id="@+id/change_content_btn3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{onClickListener}"
            android:text="list改變內(nèi)容" />


        <Button
            android:id="@+id/change_content_btn4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{onClickListener}"
            android:text="map改變內(nèi)容" />

    </LinearLayout>
</layout>

View with ID

  • 如果我們需要在Activity中獲取某個(gè)View來進(jìn)行一些操作,那該怎么辦呢?
<layout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variable name="user" type="com.luuren.bean.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <TextView 
            android:id="@+id/userName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{user.userName}"/>
   </LinearLayout>
</layout>
public class MainActivity extends AppCompatActivity {  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        ActivityMainBinding  binding = DataBindingUtil.setContentView(this, R.layout.activity_main);   
                
        binding.userName.setText("content")
    }  
}
  • 可能不是很全,暫時(shí)夠用,權(quán)當(dāng)記錄.
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容