官方Databinding常用的一些方法
Posted dx我是大雄
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了官方Databinding常用的一些方法相关的知识,希望对你有一定的参考价值。
一.公用的实体类工具类
Animal.java
package com.example.administrator.databindtext12225;
import android.databinding.ObservableField;
import android.databinding.ObservableInt;
public class Animal
public final ObservableField<String> field = new ObservableField<>();
public final ObservableInt age = new ObservableInt();
user.java
package com.example.administrator.databindtext12225;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
/**
* Created by Administrator on 2016/12/25 0025.
*/
public class User extends BaseObservable
private String name;
private String address;
private int age;
@Bindable
public String getName()
return name;
public void setName(String name)
this.name = name;
//和bindable配对使用
// notifyPropertyChanged(com.example.administrator.databindtext.BR.name);
notifyPropertyChanged(com.example.administrator.databindtext12225.BR.name);
@Bindable
public String getAddress()
return address;
public void setAddress(String address)
this.address = address;
notifyPropertyChanged(com.example.administrator.databindtext12225.BR.address);
public int getAge()
return age;
public void setAge(int age)
this.age = age;
other/user.java
package com.example.administrator.databindtext12225.other;
import android.databinding.BaseObservable;
/**
* Created by Administrator on 2016/12/25 0025.
*/
public class User extends BaseObservable
private String daxiongName;
private String daxiongAddress;
private int daxiongAge;
public String getDaxiongName()
return daxiongName;
public void setDaxiongName(String daxiongName)
this.daxiongName = daxiongName;
public String getDaxiongAddress()
return daxiongAddress;
public void setDaxiongAddress(String daxiongAddress)
this.daxiongAddress = daxiongAddress;
public int getDaxiongAge()
return daxiongAge;
public void setDaxiongAge(int daxiongAge)
this.daxiongAge = daxiongAge;
//student.java
import android.databinding.BaseObservable;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableField;
/**
* Created by Administrator on 2016/12/25 0025.
*/
public class Student extends BaseObservable
public ObservableField<String> stuName = new ObservableField<>();
public ObservableBoolean isMan = new ObservableBoolean();
private String stuAge;
public String getStuAge()
return stuAge;
public void setStuAge(String stuAge)
this.stuAge = stuAge;
MyAdapter.java
package com.example.administrator.databindtext12225;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Created by Administrator on 2016/12/25 0025.
*/
public class MyAdapter extends RecyclerView.Adapter
private ArrayList<Student> mData = new ArrayList<>();
public MyAdapter(ArrayList<Student> data)
mData.addAll(data);
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater
.from(parent.getContext()), R.layout.item_recycleview, parent, false);
ViewHolder holder = new ViewHolder(binding.getRoot());
holder.setBinding(binding);
return holder;
/**
* ViewDataBinding是我们之前用的那些binding的父类,只有自动生成的那些子类才会有setXXX方法,那现在我们需要在ViewDataBinding中设置变量咋办?这个类为我们提供了setVariable去设置变量,第一个参数是我们的变量名的引用,第二个是我们要设置的值
*当数据改变时,binding会在下一帧去改变数据,如果我们需要立即改变,就去调用executePendingBindings方法
* */
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
((ViewHolder)holder).getBinding().setVariable(com.example.administrator.databindtext12225.BR.stu,mData.get(position));
((ViewHolder)holder).getBinding().executePendingBindings();
((ViewHolder)holder).getBinding().setVariable(com.example.administrator.databindtext12225.BR.drawableId,R.mipmap.ic_launcher);
@Override
public int getItemCount()
return mData.size();
class ViewHolder extends RecyclerView.ViewHolder
private ViewDataBinding binding;
public ViewHolder(View itemView)
super(itemView);
public void setBinding(ViewDataBinding binding)
this.binding = binding;
public ViewDataBinding getBinding()
return this.binding;
Utill.java
package com.example.administrator.databindtext12225;
import android.databinding.BindingAdapter;
import android.widget.ImageView;
/**
* Created by Administrator on 2016/12/25 0025.
*/
public class Utils
@BindingAdapter("bind:image")
public static void imageLoader(ImageView imageView, int drawableId)
imageView.setBackgroundResource(drawableId);
二.Mainactivity.java
/**
* 这里主要写的是怎么把
* 1.对象 和 基本数据类型 跟view绑定
* 2.给include的布局 传递对象
* 3.@user.displayName ?? user.lastName 如果不是null 就是自身,如果是null就是user.lastName
* 4.
* <TextView android:layout_width="wrap_content"
* android:layout_height="wrap_content"
* android:text="@user.firstName, default=超哥"/>
* 5.如何 import 相同类名的class
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener
private User mUser;
private com.example.administrator.databindtext12225.other.User mOtherUser;
private ActivityMainBinding mBinding;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mUser = new User();
mUser.setName("超哥");
mUser.setAddress("北一峰");
mOtherUser = new com.example.administrator.databindtext12225.other.User();
mOtherUser.setDaxiongName("我是大雄");
mOtherUser.setDaxiongAddress("南一峰");
mBinding.setUser(mUser);
mBinding.setOtheruser(mOtherUser);
//editText 输入完成改变对象
mBinding.btOtherUserConfirm.setOnClickListener(this);
mBinding.btUserConfirm.setOnClickListener(this);
//跳转到SecondActivity
mBinding.btJump.setOnClickListener(this);
@Override
public void onClick(View view)
if (view == mBinding.btUserConfirm)
System.out.println("xcqw btUserConfirm name" + mBinding.etUserName.getText().toString() + " address " + mBinding.etUserAddress.getText().toString());
// 方法1: 这种不会立即改变View (user没有继承baseObservale)
// mUser.setName(mBinding.etUserName.getText().toString());
// mUser.setAddress(mBinding.etUserAddress.getText().toString());
// 方法2: 这种就会立即改变View(也就是重新设置一个user)
// User user = new User();
// user.setName(mBinding.etUserName.getText().toString());
// user.setAddress(mBinding.etUserAddress.getText().toString());
// mBinding.setUser(user);
// 方法3: 会立即改变View
// 1.user extends baseobservable
// 2.在get方法上@bindable
// 3.在set方法notifyPropertyChanged
mUser.setName(mBinding.etUserName.getText().toString());
mUser.setAddress(mBinding.etUserAddress.getText().toString());
else if (view == mBinding.btOtherUserConfirm)
// 方法1: 这种不会立即改变View
// System.out.println("xcqw btOtherUserConfirm name"+mBinding.etOtherUserName.getText().toString()+" address "+mBinding.etOtherUserAddress.getText().toString());
// mOtherUser.setDaxiongName(mBinding.etOtherUserName.getText().toString());
// mOtherUser.setDaxiongAddress(mBinding.etOtherUserAddress.getText().toString());
// 方法2: 这种就会立即改变View
com.example.administrator.databindtext12225.other.User user = new com.example.administrator.databindtext12225.other.User();
user.setDaxiongName(mBinding.etOtherUserName.getText().toString());
user.setDaxiongAddress(mBinding.etOtherUserAddress.getText().toString());
mBinding.setOtheruser(user);
else if (view == mBinding.btJump)
startActivity(new Intent(MainActivity.this, SecondActivity.class));
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:bind="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="user"
type="com.example.administrator.databindtext12225.User">
</variable>
<!--因为type="User"都为User类,会导致不知道到那个包,所以可以通过alias属性重命名type的类型-->
<import
alias="Other"
type="com.example.administrator.databindtext12225.other.User"/>
<variable
name="otheruser"
type="Other">
</variable>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="@layout/include_layout"
bind:user="@user"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.example.administrator.databindtext12225.MainActivity">
<TextView
android:id="@+id/tv_user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`userName`+user.name"/>
<TextView
android:id="@+id/tv_user_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`userAddress`+user.address"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.example.administrator.databindtext12225.MainActivity">
<TextView
android:id="@+id/tv_other_user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`otherUserName`+otheruser.daxiongName"/>
<TextView
android:id="@+id/tv_other_user_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`otherUserAddress`+otheruser.daxiongAddress"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/et_user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入user的name"/>
<EditText
android:id="@+id/et_user_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入user的address"/>
<Button
android:id="@+id/bt_user_confirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="确认输入,改变userView"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/et_other_user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入otheruser的name"/>
<EditText
android:id="@+id/et_other_user_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入otheruser的address"/>
<Button
android:id="@+id/bt_other_user_confirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="确认输入,改变otherUserView"/>
</LinearLayout>
<Button
android:id="@+id/bt_jump"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="跳到SecondActivity"/>
</LinearLayout>
</layout>
三.SecondActivity.java
**
* 1.一些特殊字符的转义,<String> 左右尖括号的写法
* 2.对象绑定的另外一种方法 属性都用observal
* 3.arrayList,map绑定的方法
* 4.map的两种写法
* normalMap.get(`age`)
* map[`name`]
* 5.在布局文件中可以用``拼接字符串
* */
public class SecondActivity extends AppCompatActivity
private ActivitySecondBinding mBinding;
private ObservableArrayList<com.example.administrator.databindtext12225.other.User> arrayList;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(SecondActivity.this, R.layout.activity_second);
//第一部分 普通的写法不会直接互相绑定
// final ArrayList<String> normalList = new ArrayList<>();
// normalList.add("first");
// normalList.add("second");
// mBinding.setNormalList(normalList);
//
// final Map<String, String> normalMap = new HashMap<>();
// normalMap.put("name", "zhangsan");
// normalMap.put("age", "40");
// mBinding.setNormalMap(normalMap);
//
// final String[] normalArrays = "lisi", "laowang";
// mBinding.setNormalArrays(normalArrays);
//第二部分 这么写才会互相绑定
final Animal animal = new Animal();
animal.field.set("cat");
animal.age.set(2);
mBinding.setAnimal(animal);
arrayList = new ObservableArrayList<>();
for (int i=0;i<2;i++)
com.example.administrator.databindtext12225.other.User user = new com.example.administrator.databindtext12225.other.User();
user.setDaxiongName("大熊"+i+"号");
arrayList.add(user);
mBinding.setUserList(arrayList);
final ObservableArrayList<String> list = new ObservableArrayList<>();
list.add("daxiong");
list.add("daxiong2");
mBinding.setList(list);
final ObservableArrayMap<String, String> map = new ObservableArrayMap<>();
map.put("name","Tom");
map.put("age","4");
mBinding.setMap(map);
mBinding.btChangeValue.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
// 第一部分 这么写不会互相绑定
// normalList.set(0,"hehe");
// normalList.set(1,"haha");
// normalMap.put("name","sam");
// normalMap.put("age","5");
// normalArrays[0] = "zhaosi";
//第二部分
//作用类型 对象的bindable
animal.field.set("dog");
animal.age.set(4);
list.set(0,"cat");
list.set(1,"dog");
map.put("name","Sam");
map.put("age","5");
//other/user中的属性需要加上 notifyPropertyChanged(BR.daxiongName); 才会生效,否则没用
arrayList.get(0).setDaxiongName("大熊一号改装过");
arrayList.get(1).setDaxiongName("大熊二号改装过");
);
mBinding.btJumpThirdactivity.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
startActivity(new Intent(SecondActivity.this,ThirdActivity.class));
);
Activity_second.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"
tools:context="com.example.administrator.databindtext12225.SecondActivity">
<data>
<import type="java.util.ArrayList" />
<import type="java.util.Map" />
<import type="java.lang.String" />
<import type="com.example.administrator.databindtext12225.other.User" />
<variable
name="secondActivity"
type="com.example.administrator.databindtext12225.SecondActivity">
</variable>
<!--第一部分-->
<variable
name="normalList"
type="ArrayList<String>"/>
<!--泛型的支持会在编译时期报红线,但是是可以直接运行的
但是需要通过转义字符才行,如:<数据类型> 或者<数据类型>-->
<!--< < > > 貌似这个gt可以直接用> 但是<必须被替换-->
<variable
name="normalMap"
type="Map<String,String>" />
<variable
name="normalArrays"
type="String[]" />
<!--第一部分结束-->
<!--这么写一直报错,非要写的跟下面一样,把user拿出去!!!!-->
<!--<variable-->
<!--name="user"-->
<!--type="com.example.administrator.databindtext12225.User">-->
<!--</variable>-->
<variable
name="user"
type="User">
</variable>
<variable
name="animal"
type="com.example.administrator.databindtext12225.Animal">
</variable>
<variable
name="userList"
type="android.databinding.ObservableArrayList<User>"/>
<variable
name="list"
type="android.databinding.ObservableArrayList<String>"/>
<variable
name="map"
type="android.databinding.ObservableArrayMap<String,String>"/>
</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="@normalList[0]"/>-->
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:text="@normalList[1]"/>-->
<!--<!–!!!!! `````这个符号可以凭借字符串–>-->
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:text="@normalMap.get(`age`)"/>-->
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:text="@normalArrays[0]"/>-->
<!--第一部分结束-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`animal.filed`+animal.field" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`animal.age`+String.valueOf(animal.age)" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`list[0]`+list[0]" />
<!--Map集合既可以通过map[key]的方式,也可以通过调用API-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`list[1]`+list[1]" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`map[name]`+map[`name`]" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`otheruserList[0]name`+userList[0].getDaxiongName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@`otheruserList[1]name`+userList[1].getDaxiongName" />
<Button
android:id="@+id/bt_change_value"
android:layout_width="wrap_content"
android:text="改变数据"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt_jump_thirdactivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="跳到ThirdActivity"/>
</LinearLayout>
</layout>
四.ThirdActivity.java
/**
* 1.点击事件的几种写法
* */
public class ThirdActivity extends AppCompatActivity
private ActivityThirdBinding mBinding;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(ThirdActivity.this, R.layout.activity_third);
User user = new User();
user.setName("我是第三个Activity");
mBinding.setUser(user);
// 第二种点击事件写法
mBinding.setClickEvent(new View.OnClickListener()
@Override
public void onClick(View view)
Toast.makeText(ThirdActivity.this, "xcqw 我是第二种点击事件写法", Toast.LENGTH_SHORT).show();
);
// 第三种点击事件写法
mBinding.setMyEvent(new MyEventListener()
@Override
public void clickEventOne(View view)
Toast.makeText(ThirdActivity.this, "xcqw 我是第三种写法 clickEventOne", Toast.LENGTH_SHORT).show();
@Override
public void clickEventTwo(View view)
Toast.makeText(ThirdActivity.this, "xcqw 我是第三种写法 clickEventTwo", Toast.LENGTH_SHORT).show();
@Override
public void clickEventThree(User user)
Toast.makeText(ThirdActivity.this, "xcqw 我是第三种写法 clickEventTwo username"+user.getName(), Toast.LENGTH_SHORT).show();
);
mBinding.btJumpFouractivity.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
startActivity(new Intent(ThirdActivity.this,FourActivity.class));
);
public void firstMethodClick(View view)
// 这种传统的点击事件写法还有好几种
Toast.makeText(ThirdActivity.this, "xcqw 我是第一种写法 firstMethodClick", Toast.LENGTH_SHORT).show();
Activity_third.java
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.administrator.databindtext12225.SecondActivity">
<data>
<variable
name="view"
type="android.view.View">
</variable>
<variable
name="user"
type="com.example.administrator.databindtext12225.User"/>
<variable
name="clickEvent"
type="android.view.View.OnClickListener"
/>
<variable
name="myEvent"
type="com.example.administrator.databindtext12225.MyEventListener"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/bt_first_method"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="firstMethodClick"
android:text="第一种传统写法"/>
<Button
android:id="@+id/bt_second_method"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@clickEvent"
android:text="第二种点击方式"/>
<Button
android:id="@+id/bt_third_method"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@myEvent.clickEventOne"
android:text="第三种新式写法"/>
<!--不知道() -> myEvent.clickEventThree(user) 代表什么意思-->
<Button
android:id="@+id/bt_third_method_two"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="@() -> myEvent.clickEventThree(user)"
android:text="第三种新式写法有入参"/>
<Button
android:id="@+id/bt_jump_fouractivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="跳到fourActivity"/>
</LinearLayout>
</layout>
五.FourActivitiy.java
package com.example.administrator.databindtext12225;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import com.example.administrator.databindtext12225.databinding.ActivityFourBinding;
import java.util.ArrayList;
/**
* 1.recycleView
* 2.自定义binding de set方法
* (1)现在utils方法写一个@BindingAdapter("bind:image")
public static void imageLoader(ImageView imageView, int drawableId)
imageView.setBackgroundResource(drawableId);
(2)然后在布局里面用上
<variable
name="drawableId"
type="int" />
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:image="@drawableId"/>
(3)实际用的地方
((ViewHolder)holder).getBinding().setVariable(com.example.administrator.databindtext12225.BR.drawableId,R.mipmap.ic_launcher);
// @BindingAdapter("bind:imageUrl", "bind:error")
// public static void loadImage(ImageView view, String url, Drawable error)
// Picasso.with(view.getContext()).load(url).error(error).into(view);
//
* */
public class FourActivity extends AppCompatActivity
private ActivityFourBinding mBinging;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_four);
mBinging = DataBindingUtil.setContentView(FourActivity.this, R.layout.activity_four);
mBinging.recycle.setLayoutManager(new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false));
final ArrayList<Student> mData = new ArrayList<>();
for (int i = 0;i<10;i++)
Student stu = new Student();
stu.stuName.set("我是学生 "+i);
mData.add(stu);
mBinging.recycle.setAdapter(new MyAdapter(mData));
mBinging.btChangeData.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
mData.get(4).stuName.set("hahahhahaha");
//普通写法是没用
//1 stu 中写bindable
//2 把String 写成 observableField<String>
);
Activity_four.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"
tools:context="com.example.administrator.databindtext12225.FourActivity">
<data>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycle"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
<Button
android:id="@+id/bt_change_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点我改变数据"/>
</LinearLayout>
</layout>
源码下载
以上是关于官方Databinding常用的一些方法的主要内容,如果未能解决你的问题,请参考以下文章
Android Architecture(中文官方文档)——MVVM、DataBinding、Lifecycle、Room、LiveData