Android开发之DataBinding的使用

Android开发之DataBinding的使用

Google在2015年峰会上推出的一种设计模式, 其实早在2014年已经出现.
本文只介绍了如何使用DataBinding, 没有做底层的分析, 大神请绕道 ^v^

DataBinding的配置方法

在当前Module的build.gradle下添加下面代码


android {
    dataBinding {
        enabled true
    }
}

同步工程, OK! 初次使用可能稍慢

DataBinding的基本使用

DataBinding的理念就是: No findViewById , 好, 那我们就来看看它的基本使用

先来看看如何显示数据

  1. 先来个实体类: User

    public class User {
      private String name;
      private String nickName;
      private String email;
      // setter和getter ...
  2. 设置布局. 我们就放三个TextView在屏幕中间, 用于显示用户名,昵称和邮箱, 我们用DataBinding来设置

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">
      <data>
          <!--变量-->
          <variable
              name="user"
              type="com.example.lulu.databindingdemo.User"/>
      </data>
      <LinearLayout
        ...
          >
          <TextView
              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.nickName}"/>
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@{user.email}"/>
      </LinearLayout>
    </layout>

    Note: 当编译时会默认生成一个ActivityMainBinding的类供我们在Activity中使用

  3. Activity中配置

    
    public class MainActivity extends AppCompatActivity {
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          //setContentView(R.layout.activity_main);
          //使用DataBinding的方式载入 在使用DataBinding的形式写完布局文件后会默认形成下面这样的类
          ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
          User user = new User();
          user.setName("用户名");
          user.setNickName("昵称");
          user.setEmail("example@qq.com");
          binding.setUser(user);
      }
    }

    Note: 使用上面的方式就会在Activity上显示这三个基本信息

    Paste_Image.png

现在我们更改需求, 如果我们要求用户有Vip, 根据是否是Vip来设置用户名的颜色, 该怎么办呢 ?

  1. 修改实体类, 添加boolean vip; 字段

  2. 修改布局中 用户名 的TextView

    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textColor="@{user.vip ? 0xffff0000 : 0xff000000}"
      android:text="@{user.name}"/>
  3. 修改MainActivity, 添加设置Vip的set方法, 成功实现

    Paste_Image.png

    Note: 通过上面可以看出在@{}中可以写一些简单的表达式, 例如:赋值表达式,连接表达式等

那我们接着变化需求: 如果我们需要在一个控件中显示并且符合这种形式: 昵称(用户名), 此时需要注意如何在@{}中写”“呢 ?, 修改代码如下

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{user.nickName + `(` + user.name + `)`}"
    android:textColor="@{user.vip ? 0xffff0000 : 0xff000000}"/>

Note: 使用键盘上 1 键左边的按键

Paste_Image.png

有些情况下需要对某一对象判空操作, 可以使用 ??, 例如:

android:text="@{user.nickName ?? user.name}"

Note: 如果左侧为空则显示右侧的, 若左侧不为空则显示左侧的
对于在@{}中书写某些符号,例如 “>”和”<”符号,这些符号都是与xml中的标记有冲突的应使用转义字符代替, 如:

&gt; 和 &lt;

DataBinding的监听设置

现在我们增加需求, 要求可以点击用户名和长按昵称分别弹出Toast

  1. 在实体类中添加下面的两个方法, 一个是点击用户名一个是长按昵称

    public void clickName(View view) {
      Toast.makeText(view.getContext(), "点击用户名", Toast.LENGTH_SHORT).show();
    }
    
    public boolean longClickNickName(View view) {
      Toast.makeText(view.getContext(), "长按昵称", Toast.LENGTH_SHORT).show();
      return true;
    }
  2. 修xml文件

    <TextView
      android:onClick="@{user.clickName}"
      ...
      />
    <TextView
      android:onLongClick="@{user.longClickNickName}"
      ...
      />
    

    DataBinding.gif

注意事项

  1. xml中onClick后面的方法名必须和实体类中方法名完全相同
  2. 参数列表和返回值类型必须和监听方法是一样的, 否则会报以下的异常:
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Listener class android.view.View.OnLongClickListener with method onLongClick did not match signature of any method user.longClickNickName

再来修改需求, 要求屏幕显示两个用户, 并且可以传入两个不同的用户
可以考虑使用include实现引入布局文件, 但是数据怎样传入呢 ?

  1. 增加user_layout.xml文件

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">
    
      <data>
          <!--变量-->
          <variable
              name="user"
              type="com.example.lulu.databindingdemo.User"/>
      </data>
    
      <LinearLayout
          android:id="@+id/activity_main"
          android:layout_width="0dp"
          android:layout_weight="1"
          android:layout_height="match_parent"
          android:gravity="center"
          android:orientation="vertical"
          tools:context="com.example.lulu.databindingdemo.MainActivity">
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:onClick="@{user.clickName}"
              android:text="@{user.nickName + `(` + user.name + `)`}"
              android:textColor="@{user.vip ? 0xffff0000 : 0xff000000}"/>
    
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:onLongClick="@{user.longClickNickName}"
              android:text="@{user.nickName}"/>
    
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@{user.email}"/>
      </LinearLayout>
    </layout>
  2. 修改activity_main.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>
          <!--导入-->
          <import type="com.example.lulu.databindingdemo.User"/>
          <!--变量-->
          <variable
              name="users"
              type="java.util.List&lt;User&gt;"/>
      </data>
      <LinearLayout
          android:id="@+id/activity_main"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center"
          android:orientation="horizontal"
          tools:context="com.example.lulu.databindingdemo.MainActivity">
          <include layout="@layout/user_layout" app:user="@{ users[0] }"/>
          <include layout="@layout/user_layout" app:user="@{ users[1] }"/>
      </LinearLayout>
    </layout>

    Note: 使用include导入user的布局文件, app:user中的user与user_layout.xml中的user变量对应

  3. 修改Activity文件

    User user = new User();
    user.setName("用户名");
    user.setNickName("昵称");
    user.setEmail("example@qq.com");
    user.setVip(true);
    
    User user1 = new User();
    user1.setName("新用户名");
    user1.setNickName("新昵称");
    user1.setEmail("new@qq.com");
    user1.setVip(false);
    
    List<User> list = new ArrayList<>();
    list.add(user);
    list.add(user1);
    binding.setUsers(list);
    

Paste_Image.png

DataBinding的增加自定义属性

我们知道从网络获取的图片我们一般在实体类中只保存其网络地址, 这个时候我们发现如何使用DataBinding呢 ? (上代码)

  1. 写一个工具类, 用于将Url和ImageView进行绑定

    public class Utils {
      @BindingAdapter({"imageUrl"})
      public static void loadImage(ImageView imageView, String url) {
          if (TextUtils.isEmpty(url)) {
              //如果网址为空, 默认加载ic_launcher
              imageView.setImageResource(R.mipmap.ic_launcher);
          } else {
              //使用Glide加载图片
              Glide.with(imageView.getContext()).load(url).into(imageView);
          }
      }
    }

    Note:这个地方使用@BindingAdapter注解来说明这个方法所绑定名称. 注意, 第一个参数一定要是View, 从第二个参数开始跟注解中名称相对应
    注意, 此处的方法一定是static的, 非static的下面会介绍到

  2. 修改实体类, 添加icon字段, 在Activity中设置icon地址

    user.setIcon("http://upload-images.jianshu.io/upload_images/3118842-b48fbee83f5a5c8b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240");
  3. 修改user_layout.xml文件添加ImageView

    <ImageView
      app:imageUrl="@{user.icon}"
      android:layout_width="100dp"
      android:layout_height="100dp"/>

    Paste_Image.png

考虑使用在ListView中使用DataBinding

  1. 写一个通用的ListView的Adapter, 针对于单布局

    /**
    * Created by lulu on 2016/12/9.
    * 通用的ListView的Adapter (单布局)
    */
    public class CommonAdapter<T> extends BaseAdapter {
      private Context mContext;
      private List<T> mList;
      private int mLayoutId;
      private int mVariableId;
    
      public CommonAdapter(Context context, List<T> list, int layoutId, int variableId) {
          mContext = context;
          mList = list;
          mLayoutId = layoutId;
          mVariableId = variableId;
      }
    
      @Override
      public int getCount() {
          return mList.size();
      }
    
      @Override
      public Object getItem(int i) {
          return mList.get(i);
      }
    
      @Override
      public long getItemId(int position) {
          return position;
      }
    
      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
          ViewDataBinding binding = null;
          if (convertView == null) {
              binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), mLayoutId, parent, false);
          } else {
              binding = DataBindingUtil.getBinding(convertView);
          }
          binding.setVariable(mVariableId, mList.get(position));
          return binding.getRoot();
      }
  2. 添加item.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">
      <data>
          <variable
              name="user"
              type="com.example.lulu.databindingdemo.User"/>
      </data>
      <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="horizontal">
          <ImageView
              android:layout_width="100dp"
              android:layout_height="100dp"
              app:imageUrl="@{user.icon}"/>
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="match_parent"
              android:gravity="center"
              android:text="@{user.name}"/>
      </LinearLayout>
    </layout>
  3. 在主布局中添加ListView控件

    <data>
    <variable
        name="adapter"
        type="android.widget.BaseAdapter"/>
    </data>
    ...
    <ListView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:adapter="@{adapter}"/>
  4. Activity中添的假数据

    List<User> users = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
      User user = new User();
      user.setName("用户" + i);
      user.setIcon("http://upload-images.jianshu.io/upload_images/3118842-b48fbee83f5a5c8b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240");
      users.add(user);
    }
    CommonAdapter<User> adapter = new CommonAdapter<>(this, users, R.layout.item, BR.user);
    binding.setAdapter(adapter);

    DataBinding01.gif

现在需要添加上相应的点击事件

我们要在点击时做出某种动作并且及时通知刷新当前ListView的数据

  1. 修改User实体类, 继承BaseObservable用于监听ListView的数据源的变化

  2. 给需要通知的属性的getter方法加上@Bindable注解

    @Bindable
    public String getName() {
      return name;
    }
  3. 在User类中写一个点击方法

    public void click(View view) {
      setName(getName() + "(已点击)");
      //刷新某个属性
      notifyPropertyChanged(BR.name);
    }
  4. 在item.xml中给相应布局加上点击事件

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:onClick="@{ user.click}"
        android:orientation="horizontal">
        <ImageView
            .../>
        <TextView
            .../>
    </LinearLayout>

    DataBinding02.gif

Component的使用

在上面的字符串类型的url和ImageView绑定时说过, 那个Utils中的方法只能是static的, 非static将在这边讲到
这种方式的好处是可以访问this, 实现某些借口, 这是使用static方法所不能实现的

  1. 修改之前的Utils类, 去掉loadImage方法的static关键字

    如果此时运行会crash掉, 抛出以下异常:
    Paste_Image.png

  2. 新建MyComponent类, 实现DataBindingComponent接口, 会发现此时会有一个与Utils对应的实现方法

    public class MyComponent implements DataBindingComponent {
    private Utils mUtils;
    @Override
    public Utils getUtils() {
        if (mUtils == null) {
            mUtils = new Utils();
        }
        return mUtils;
    }
    }
  3. 在Activity中设置Component

    DataBindingUtil.setDefaultComponent(new MyComponent());

Demo地址

菜鸟一枚, Demo奉上:https://github.com/changer0/DataBindingDemo

致谢马老师视频课程


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值