DataBinding的存在是为了脱离Controller与View之间的引用联系。如下图所示
这样,Controller只处理与业务逻辑相关的操作。Controller与View之间相互独立,精简了编写代码的数量,同时便于维护。
DataBinding的使用
首先再build.gradle中开启Databinding
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.databinding"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
dataBinding {
enabled true
}
}
转换xml为databing格式,也就是在最外层添加<layout标签>
<?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"> <!--这里表示要绑定的ViewModel对象--> <data> <variable name="data" type="com.example.databinding.MyViewModel" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{String.valueOf(data.number)}" android:textSize="30sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.21" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button" android:onClick="@{()->data.add()}" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
在Activity中,极大简化了Activity的逻辑
package com.example.databinding; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class MyViewModel extends ViewModel { private MutableLiveData<Integer> number; public MutableLiveData<Integer> getNumber() { if (number == null) { number = new MutableLiveData<>(); number.setValue(0); } return number; } public void add() { number.setValue(number.getValue()+1); } }
package com.example.databinding; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.ViewModelProviders; import android.os.Bundle; import com.example.databinding.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { MyViewModel myViewModel; ActivityMainBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this,R.layout.activity_main); myViewModel = ViewModelProviders.of(this).get(MyViewModel.class); binding.setData(myViewModel); binding.setLifecycleOwner(this); } }