Android-DataBinding入门1
Google在15年的发布大会上提出了DataBinding数据绑定框架,解决了Android编程的一大痛点。官方原生支持MVVM模型让我们可以在不改变既有的框架上使用上新的特性。它可以使我们的代码更加简洁,不必在页面中写太多的findViewById,省时省力。今天我们也体验了一把,记录下遇到的问题和简单的入门介绍下。
1、Android Studio需要更新到 1.3 版本,而且需要开启DataBinding功能:
在build.gradle配置:
android{
	dataBinding{
		enabled = true
	}
}
2、布局
布局中,根节点要以layout开头,声明数据使用data标签。在data中可以为数据对象声明变量,引入要使用的类等。
(1)在具体控件中使用对象的数据也挺简单的,使用@{对象变量.对象属性}就可以取出数据了;
(2)支持绑定事件:@{对象.方法名(参数)}。
代码如下:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- DataBinding 现在根节点layout -->
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 绑定的数据对象 -->
    <data>
        <!-- 为数据对象声明变量:user,取出属性的用法:@{user.userName} -->
        <variable
            name="user"
            type="com.ha.cjy.databingdemo.model.UserModel"/>
        <variable
            name="presenter"
            type="com.ha.cjy.databingdemo.MainActivityPresenter"/>
    </data>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_margin="12dp"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="12dp"
            android:textSize="16sp"
            android:background="@android:color/white"
            android:textColor="@color/colorPrimary"
            android:hint="显示用户名"
            android:text="@{user.userName}"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:padding="12dp"
            android:textSize="16sp"
            android:background="@android:color/white"
            android:textColor="@color/colorPrimary"
            android:hint="显示手机号码"
            android:text="@{user.telPhone}"
            />
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="12dp"
            android:background="@color/colorPrimary"/>
        <EditText
            android:id="@+id/et_userName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:padding="12dp"
            android:textSize="16sp"
            android:background="@android:color/white"
            android:textColor="@color/colorPrimary"
            android:hint="输入用户名"
            />
        <EditText
            android:id="@+id/et_telPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:padding="12dp"
            android:textSize="16sp"
            android:background="@android:color/white"
            android:textColor="@color/colorPrimary"
            android:hint="输入手机号码"
            />
        <Button
            android:id="@+id/btn_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:padding="12dp"
            android:textSize="16sp"
            android:background="@color/colorPrimary"
            android:textColor="#FFFFFF"
            android:text="更新数据"
            android:onClick="@{presenter.onClickEvent}"
            />
    </LinearLayout>
</layout>
3、代码
在ManiActivity中,需要为布局和数据进行绑定操作:DataBindingUtil.setContentView(Activity activity, int layoutId)
package com.ha.cjy.databingdemo;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.ha.cjy.databingdemo.databinding.ActivityMainBinding;
import com.ha.cjy.databingdemo.model.UserModel;
public class MainActivity extends AppCompatActivity implements MainActivityPresenter{
    //对应的是layout文件名,后缀Binding,这个是自动生成的
    private ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        binding.setPresenter(this);
        UserModel userModel = new UserModel("测试姓名","18012365485");
        binding.setUser(userModel);
    }
    @Override
    public void onClickEvent(View view) {
    	//注意:使用DataBinding,控件的获取应该使用DataBinding对象,而不是通过findViewById获取(这样的方式获取不到控件的文本内容)
        userModel.setUserName(binding.etUserName.getText().toString());
        userModel.setTelPhone(binding.etTelPhone.getText().toString());
        binding.setUser(userModel);
    }
}
这样子做,就完成了一个简单的dataBinding的使用,代码也比以前简洁了许多。
但是,看到这里,同学们不禁要问了:“不是说dataBinding的核心功能是实现单向数据绑定呀,没有看到呀,还是以前取出输入的文本重新赋值的做法,只是实现形式不一样而已。”
没错,这样的做法确实没有体现出单向绑定数据功能。接下来,我们来改造一下代码。
package com.ha.cjy.databingdemo;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.ha.cjy.databingdemo.databinding.ActivityMainBinding;
import com.ha.cjy.databingdemo.model.UserModel;
public class MainActivity extends AppCompatActivity implements MainActivityPresenter{
    //对应的是layout文件名,后缀Binding,这个是自动生成的
    private ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //进行DataBinding绑定
        binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        binding.setPresenter(this);
        UserModel userModel = new UserModel("测试姓名","18012365485");
        binding.setUser(userModel);
    }
    @Override
    public void onClickEvent(View view) {
        //注意:使用DataBinding,控件的获取应该使用DataBinding对象,而不是通过findViewById获取(这样的方式获取不到控件的文本内容)
        binding.getUser().setUserName(binding.etUserName.getText().toString());
        binding.getUser().setTelPhone(binding.etTelPhone.getText().toString());
    }
}
看下这句代码:binding.getUser().setUserName(binding.etUserName.getText().toString());我们使用dataBinding获取声明过的User对象,然后为其属性userName赋值。看到这里,我们也只是看到更改了数据,没有看到任何更新UI的代码。不要急,我们接着看一下数据类UserModel的实现就明白了。
package com.ha.cjy.databingdemo.model;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import com.ha.cjy.databingdemo.BR;
/**
 * 用户
 * Created by cjy on 17/12/5.
 */
public class UserModel extends BaseObservable {
    /**
     * 用户名
     */
    //注解 数据变动更新UI更新
    @Bindable
    private String userName;
    /**
     * 手机号码
     */
    @Bindable
    private String telPhone;
    public UserModel() {
    }
    public UserModel(String userName, String telPhone) {
        this.userName = userName;
        this.telPhone = telPhone;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
        //与@Bindable配合使用,数据有更新,通知UI跟着更新
        notifyPropertyChanged(BR.userName);
    }
    public String getTelPhone() {
        return telPhone;
    }
    public void setTelPhone(String telPhone) {
        this.telPhone = telPhone;
        notifyPropertyChanged(BR.telPhone);
    }
}
由上面代码中,我们看到了注解Bindable,这个是用来标识属性是否有变动。官方介绍如下:
The Bindable annotation should be applied to any getter accessor method of an
 * {@link Observable} class. Bindable will generate a field in the BR class to identify
 * the field that has changed.
当然了,只是标识属性变动是不够的,这时还是没有通知UI更新的。我们需要使用notifyPropertyChanged方法,告知UI数据变化了从而更新UI。注意,notifyPropertyChanged方法的参数需要使用BR.属性名才可以。dataBinding在BR类中为对象属性生成了唯一的标识码。
总结
看到这里基础的入门介绍就讲完了,其实还有很多更高级的用法,比如在RecyclerView中怎么用等等,大家可以去自己查阅资料学习,这样认识的可以更深刻。希望这篇文章对大家能够有所帮助。
Android-DataBinding入门1的更多相关文章
- [译]:Xamarin.Android开发入门——Hello,Android Multiscreen深入理解
		原文链接:Hello, Android Multiscreen_DeepDive. 译文链接:Xamarin.Android开发入门--Hello,Android Multiscreen深入理解. 本 ... 
- [译]:Xamarin.Android开发入门——Hello,Android深入理解
		返回索引目录 原文链接:Hello, Android_DeepDive. 译文链接:Xamarin.Android开发入门--Hello,Android深入理解 本部分介绍利用Xamarin开发And ... 
- [译]:Xamarin.Android开发入门——Hello,Android快速上手
		返回索引目录 原文链接:Hello, Android_Quickstart. 译文链接:Xamarin.Android开发入门--Hello,Android快速上手 本部分介绍利用Xamarin开发A ... 
- Hello, Android 快速入门
		Hello, Android Android 开发与 Xamarin 简介 在这两节指南中,我们将 (使用 Xamarin Studio或 Visual Studio)建立我们的第一个 Xamarin ... 
- Android工程师入门(二)——不忙不累怎么睡。。
		安卓开发迫在眉睫,这周入个门吧! Android工程师入门(二) 四.在界面中显示图片 ImageView 是显示图片的一个控件. --属性 src——内容图片: background——背景图片/背 ... 
- [电子书] 《Android编程入门很简单》
		<Android编程入门很简单>是一本与众不同的Android学习读物,是一本化繁为简,把抽象问题具体化,把复杂问题简单化的书.本书避免出现云山雾罩.晦涩难懂的讲解,代之以轻松活泼.由浅入 ... 
- Android实现入门界面布局
		Android实现入门界面布局 开发工具:Andorid Studio 1.3 运行环境:Android 4.4 KitKat 代码实现 首先是常量的定义,安卓中固定字符串应该定义在常量中. stri ... 
- Android从入门到精通pdf+书源代码
		不须要积分,免费放送 Android从入门到精通的pdf,入门的好书籍,因为csdn文件大小的限制所以分成了两部分. part1地址:http://download.csdn.net/detail/a ... 
- 设计模式笔记之三:Android DataBinding库(MVVM设计模式)
		本博客转自郭霖公众号:http://mp.weixin.qq.com/s?__biz=MzA5MzI3NjE2MA==&mid=2650236908&idx=1&sn=9e53 ... 
- 教我徒弟Android开发入门(一)
		前言: 这个系列的教程是为我徒弟准备的,也适合还不懂java但是想学android开发的小白们~ 本系列是在Android Studio的环境下运行,默认大家的开发环境都是配置好了的 没有配置好的同学 ... 
随机推荐
- fedora 19 gnome 3.8 关闭笔记本盖子的动作
			gnome-tweak-tool里没有了相关选项,但是又想让关闭盖子不挂起,后来看看才知道gnome3.8不再提供这功能,而是交给systemd来处理,所以估计用dconf-edit在gnome的po ... 
- js页面间通信方法(storage事件)(浏览器页面间通信方法)
			在写页面的时候有时会遇到这样的需求,需要两个页面之间传递数据或者一个事件.这个时候,就需要用到我今天所要讲的storage事件,学习这个事件之前,需要先了解localStorage的用法.具体用法可以 ... 
- JqueryMobile基础之创建页面
			首先简答介绍一下JQueryMobile吧,我觉得用一句话来讲就是可以 "写更少的代码,做更多的事情" : 它可以通过一个灵活及简单的方式来布局网页,且兼容所有移动设备.这也是我自 ... 
- 为什么String类是不可变的?
			为什么String类是不可变的? String类 什么是不可变对象 当满足以下条件时,对象才是不可变的: 对象创建以后其状态就不能修改. 对象的所有域都是final类型的. 对象是正确创建的(在对象的 ... 
- python 使用标准库根据进程名获取进程的pid
			有时候需要获取进程的pid,但又无法使用第三方库的时候. 方法适用linux平台. 方法1 使用subprocess 的check_output函数执行pidof命令 from subprocess ... 
- mysql 安装配置
			l 下载压缩包: 官网下载地址:https://dev.mysql.com/downloads/mysql/5.1.html#downloads 第一步: 将下载的压缩包解压到你要安装的目录下 第二 ... 
- linux学习(六)绝对路径、相对路径、cd、mkdir、rmdir、rm
			一.绝对路径 就是从根开始的,如:/root./usr/local. 二.相对路径 相对于当前路径的,比如我们在当前路径下建立了一个a.txt. [root@iZ25lzba47vZ ~]# pwd ... 
- js中的引用类型和基本类型
			基本类型 : Undifined.Null.Boolean.Number和String 引用类型 :Object .Array .Function .Date等. 基本数据类型保存在栈内存中 是按值访 ... 
- Python 读取某个目录下的文件
			读取某个目录下的文件,如'/Users/test/test_kmls'目录下有test1.txt.test2.txt. 第一种方法读出的all_files是test1.txt.test2.txt im ... 
- 图片格式   WebP   APNG
			WebP 是一种支持有损压缩和无损压缩的图片文件格式,派生自图像编码格式 VP8.根据 Google 的测试,无损压缩后的 WebP 比 PNG 文件少了 45% 的文件大小,即使这些 PNG 文件 ... 
