Android Data Binding代碼實戰

本文介紹使用Android Data Binding技術,結合豆瓣電影搜索API,在RecycleView中展示電影列表。

data-binding-example
data-binding-example

代碼實現

我根據MVVM(Model-View-ViewModel)的順序介紹代碼實現。

Model層

Model層我定義了一個Movie類,要獲得通知UI更新的功能,需要繼承BaseObservable類;
如果要能被View綁定,需要在get方法上添加@Bindable標注,同時在set方法中要調用notifyPropertyChanged(BR.title)方法通知View更新。

BR類會根據@Bindable標注自動生成

public class Movie extends BaseObservable {
    private String id;
    private String title;
    private String original_title;
    private String year;
    private Images images;
    private Rating rating;

    @Bindable
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
        notifyPropertyChanged(BR.title);
    }

    @Bindable
    public String getDescription() {
       return this.original_title + "\n" + this.getYear();
    }

    public void setOriginal_title(String original_title) {
        this.original_title = original_title;
        notifyPropertyChanged(BR.description);
    }

    public void setYear(String year) {
        this.year = year;
        notifyPropertyChanged(BR.description);
    }

    ...
   }

我定義了一個getDescription方法,將original_title和year組合在一起,
在View層也能進行綁定,getDescription相關的字段值發生變化后,
需要在set方法中調用notifyPropertyChanged通知View更新內容。

View層

需要在布局文件中使用layout作為最外層布局,同時在其中的data區域中聲明一個movie變量,
并指定類型為我們在Model中定義的Movie類。

在View中使用@{movie.title}這樣的表達式, 將變量進行綁定。

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="movie"
            type="com.aswifter.databinding.model.Movie" />
    </data>

    ...
    <ImageView
        android:id="@+id/ivMovie"
        android:layout_width="109dp"
        android:layout_height="135dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{movie.title}"
            android:textAppearance="@style/TextAppearance.AppCompat.Title"
            android:textColor="@color/primary_text" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:text="@{movie.description}"
            android:textColor="@color/secondary_text" />


        <RatingBar
            style="@android:style/Widget.DeviceDefault.Light.RatingBar.Small"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:numStars="10"
            android:rating="@{movie.rating.average}"
            android:stepSize="0.5" />
    </LinearLayout>

   ...
</layout>

ViewModel層

定義好了Model和View之后,需要把兩者連起來,當Model的數據變化后,自動更新View。

Android Data Binding中的ViewModel是根據layout自動生成的Binding類,
如果layout的名稱是movie_item.xml,生成的Binding類名稱就是MovieItemBinding。

  • 創建Binding類
    在RecyclerView的Adapter的onCreateViewHolder中創建Binding類
MovieItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),        
                                                   R.layout.movie_item,  parent,  false);
  • 設置變量值
    在onBindViewHolder中設置layout中定義的movie變量值
Movie movie = mMovies.get(position);      
holder.binding.setVariable(com.aswifter.databinding.BR.movie, movie);
holder.binding.executePendingBindings();
  • 顯示圖片
    使用Glide顯示圖片,ivMovie是MovieItemBinding根據ImageView的id自動生成的
Glide.with(MovieActitiviy.this)
        .load(movie.getImages().getMedium())
        .fitCenter()
        .into(holder.binding.ivMovie);

DataBinding參考

可以閱讀以下文章:

Android中的Data Binding初探 (一)

Android中的Data Binding初探 (二)

Android中的Data Binding初探 (三)

一些感想

  • Model的定義還是比較麻煩,需要寫標注和通知方法,希望后續有相應的Android Studio插件自動生成。
  • Binding類自動生成View對應的字段,不用寫findViewById了,這點很爽。
  • 代碼結構更清晰,使用MVVM模式分層的思想,Model層只負責數據,
    我把網絡請求和Json解析的方法都寫到Model中,Activity基本上與Model解耦了,
    以后更換接口,HTTP庫或JSON庫,都不需要動Activity,代碼測試也更方便。
  • Data Binding目前只能實現單向綁定,期待以后能支持雙向綁定。

Github

代碼已經發布到Github,
源碼地址:AndroidDataBindingExample

本文作者: 陽春面
原文地址:http://www.aswifter.com/2015/07/11/android-data-binding-example/

歡迎關注我的微信公眾號,分享Android 開發,IOS開發,Swift開發和互聯網內容
微信號:APP開發者

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容