dataBinding使用(一)
【1】首先需要配置
在module的build.gradle中配置
dataBinding{enabled=true
}
具体位置如下:
【2】创建一个数据类用于获取和设置数据
两种写法
[1]传统变量 get/set
public class TestVM extends BaseObservable{private String name;private String nickName;@Bindablepublic String getName() {return name;}public void setName(String name) {this.name = name;notifyPropertyChanged(BR.name);}@Bindablepublic String getNickName() {return nickName;}public void setNickName(String nickName) {this.nickName = nickName;notifyPropertyChanged(BR.nickName);}
}
这种要记得
(1)类名继承BaseObservable,否则编译会报错:
* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
(2)在get方法前加@Bindable(然后编译,变量会被添加的BR.java文件中),否咋下一步找不到变量,编译成功后
(3)在set方法中更新数据
notifyPropertyChanged(BR.name);
[2]观察者:Observable是个接口,Google为我们提供了一个BaseObservable类,我们只要把Model类继承自它就获得了通知UI更新数据的能力(个人更喜欢用)
public class TestVM {public ObservableField<String> name = new ObservableField<>();public ObservableField<String> nickName = new ObservableField<>();
}
【3】页面布局
初始创建一个xml文件如下,在根视图(下图的根视图为LinearLayout)alt+enter,会弹出选框,选择将其转换为dataBinding布局
[1]添加data数据,import为引用,name为VM数据类的名称,后续布局需要此名称获取数据变量
[2]在页面中添加两个textView和一个button用于点击显示,单向绑定中VM数据下方格式表达
"@{viewModel.name}"
<?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><import type="android.view.View" /><variablename="viewModel"type="com.tzbc.databindtest.TestVM" /></data><LinearLayoutandroid:id="@+id/linearLayout"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center_horizontal"android:orientation="vertical"><TextViewandroid:id="@+id/tvName"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center"android:hint="@string/hintName"android:text="@{viewModel.name}"android:textSize="25sp" /><TextViewandroid:id="@+id/tvNickName"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="20dp"android:gravity="center"android:hint="@string/hintNickName"android:text="@{viewModel.nickName}"android:textSize="25sp" /><Buttonandroid:id="@+id/button"android:layout_width="match_parent"android:layout_height="50dp"android:layout_marginTop="20dp"android:layout_marginStart="20dp"android:layout_marginEnd="20dp"android:text="@string/app_name"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent" /></LinearLayout>
</layout>
【4】Activity
package com.tzbc.databindtest;import android.os.Bundle;
import android.view.View;
import android.widget.Button;import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;import com.tzbc.databindtest.databinding.ActivityMainBinding;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private TestVM testVM;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);testVM = new TestVM();activityMainBinding.setViewModel(testVM);activityMainBinding.button.setOnClickListener(this);}@Overridepublic void onClick(View v) {testVM.name.set("桃子不出");testVM.nickName.set("tzbc");}
}
点击button后:
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
PS:双向绑定,editText,用户实时输入也能存储在变量中
VM增加变量:
public ObservableField<String> editContent = new ObservableField<>();
布局更新(注意是@={ xx.xx},“=”标识双向绑定):
在activity里实时监听editText,会发现输入会被更新到VM变量中:
package com.tzbc.databindtest;import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;import com.tzbc.databindtest.databinding.ActivityMainBinding;public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {private static final String TAG = "tzbc";private TestVM testVM;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);testVM = new TestVM();activityMainBinding.setViewModel(testVM);activityMainBinding.button.setOnClickListener(this);activityMainBinding.etContent.addTextChangedListener(this);}@Overridepublic void onClick(View v) {testVM.name.set("桃子不出");testVM.nickName.set("tzbc");}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count, int after) {}@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {String currentEditContent = testVM.editContent.get();Log.e(TAG, "currentEditContent : " + currentEditContent);}@Overridepublic void afterTextChanged(Editable s) {}
}
查看打印log: