Android Data Binding代码实战

本文介绍使用Android Data Binding技术,结合豆瓣电影搜索API,在RecycleView中展示电影列表。

《Android Data Binding代码实战》 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开发者

《Android Data Binding代码实战》

    原文作者:阳春面
    原文地址: https://www.jianshu.com/p/5400f5f64f85
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞