基本使用
关于DataBinding的使用可以直接参考官网数据绑定库介绍,此处就直接忽略。本篇主要是阐述DataBinding是如何实现liveData的数据更新到对应xml布局
准备Demo
直接clone如下demo
git clone https://github.com/xiaobaoyihao/AndroidDataBindingDemo.git
该样例就是实现最简单的DataBinding
绑定类
绑定类是用于访问布局的变量和视图,所有绑定类都是继承ViewDataBinding抽象类的。
demo中引入了数据绑定和视图绑定,所以系统会为每个布局文件生成一个绑定类。默认情况下,类名称基于布局文件的名称,它会转换为 Pascal 大小写形式并在末尾添加 Binding 后缀。以本demo中fragment_main.xml为例生成的对应类为 FragmentMainBinding。关于绑定类的使用可以直接参考官网使用文档
我们以本例中FragmentMainBinding为例进行分析
我们先看MainFragment代码
class MainFragment : Fragment() {
companion object {
fun newInstance() = MainFragment()
}
private lateinit var viewModel: MainViewModel
private lateinit var mBinding: FragmentMainBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
mBinding = FragmentMainBinding.inflate(layoutInflater, container, false)
return mBinding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
mBinding.lifecycleOwner = viewLifecycleOwner
mBinding.fvm = viewModel
}
}
MainFragment执行了执行了绑定类的inflate静态方法返回了绑定类对象,而其中root成员变量就是对应布局文件的根视图
对应布局
<?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>
<variable
name="fvm"
type="com.dbs.databinding.demo.ui.main.MainViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dbs.databinding.demo.ui.main.MainFragment">
<TextView
android:id="@+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@{String.valueOf(fvm.MClickedCount)}"
android:textSize="25dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="0" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="@{fvm::onClickBtn}"
android:text="button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/message" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
viewModel也非常简单
class MainViewModel : ViewModel() {
var mClickedCount = MutableLiveData(0)
fun onClickBtn(view: View) {
// mCLickCount++
mClickedCount.value = mClickedCount.value?.inc()?: 0
}
}
主要实现就是通过按钮点击来实现TextView文本修改;为了有针对性分析,我们以问题形式进行展开分析说明
Q1:FragmentMainBinding.inflate返回了什么?
首先我们从build/data_binding_base_class_source_out目录下找到这个FragmentMainBinding
可以看到MainFragmentBinding类为抽象类,该类引用了对应布局文件的view(带有id的)以及在布局文件中声明的viewModule成员变量和bind、inflate相关方法,我们思路回到inflate方法中
// FragmentMainBinding.java
@NonNull
public static FragmentMainBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup root, boolean attachToRoot) {
return inflate(inflater, root, attachToRoot, DataBindingUtil.getDefaultComponent());
}
@NonNull
@Deprecated
public static FragmentMainBinding inflate(@NonNull LayoutInflater inflater,
@Nullable ViewGroup root, boolean attachToRoot, @Nullable Object component) {
return ViewDataBinding.<FragmentMainBinding>inflateInternal(inflater, R.layout.fragment_main, root, attachToRoot, component);
}
// ViewDataBinding.java
protected static <T extends ViewDataBinding> T inflateInternal(
@NonNull LayoutInflater inflater, int layoutId, @Nullable ViewGroup parent,
boolean attachToParent, @Nullable Object bindingComponent) {
return DataBindingUtil.inflate(
inflater,
layoutId,
parent,
attachToParent,
checkAndCastToBindingComponent(bindingComponent)
);
}
public class DataBindingUtil {
private static DataBinderMapper sMapper = new DataBinderMapperImpl();
public static <T extends ViewDataBinding> T inflate(
@NonNull LayoutInflater inflater, int layoutId, @Nullable ViewGroup parent,
boolean attachToParent, @Nullable DataBindingComponent bindingComponent) {
final boolean useChildren = parent != null && attachToParent;
final int startChildren = useChildren ? parent.getChildCount() : 0;
final View view = inflater.inflate(layoutId, parent, attachToParent);
if (useChildren) {
return bindToAddedViews(bindingComponent, parent, startChildren, layoutId);
} else {
return bind(bindingComponent, view, layoutId);
}
}
static <T extends ViewDataBinding> T bind(DataBindingComponent bindingComponent, View root,
int layoutId) {
return (T) sMapper.getDataBinder(bindingComponent, root, layoutId);
}
}
这里面的sMapper类型为androidx.databinding.DataBinderMapperImpl,需要提下每个模块都有同名的DataBinderMapperImpl,app模块存在二个同名但路径不一样;sMapper可以理解为映射表入口类它引用了appl模块中DataBinderMapperImp
可以清楚看到DataBinderMapperImpl构造器中调用了addMapper方法;我们继续看getDataBinder方法
@Override
public ViewDataBinding getDataBinder(DataBindingComponent bindingComponent, View view,
int layoutId) {
for(DataBinderMapper mapper : mMappers) {
ViewDataBinding result = mapper.getDataBinder(bindingComponent, view, layoutId);
if (result != null) {
return result;
}
}
if (loadFeatures()) {
return getDataBinder(bindingComponent, view, layoutId);
}
return null;
}
可以看到绑定类的查找是依次遍历项目中所有DataBinderMapperImpl类来搜查绑定类;那么项目中的所有模块的DataBinderMapperImpl是如何添加到mapper列表中呢?我们从上图中看到构造器中调用了addMapper方法
public void addMapper(DataBinderMapper mapper) {
Class<? extends DataBinderMapper> mapperClass = mapper.getClass();
if (mExistingMappers.add(mapperClass)) {
mMappers.add(mapper);
final List<DataBinderMapper> dependencies = mapper.collectDependencies();
for(DataBinderMapper dependency : dependencies) {
addMapper(dependency);
}
}
}
上面代码可以看到mMappers维护了apk所有依赖的DataBinderMapper映射表;先是添加app模块的映射表,然后将其依赖的映射表依次添加到mMappers中;本demo中最终调用了com.example.demo.DataBinderMapperImpl.getDataBinder方法
public class DataBinderMapperImpl extends DataBinderMapper {
private static final int LAYOUT_FRAGMENTMAIN = 1;
static {
INTERNAL_LAYOUT_ID_LOOKUP.put(com.example.demo.R.layout.fragment_main, LAYOUT_FRAGMENTMAIN);
}
public ViewDataBinding getDataBinder(DataBindingComponent component, View view, int layoutId) {
// 通过布局资源id以及根view的tag来进行指定绑定类
int localizedLayoutId = INTERNAL_LAYOUT_ID_LOOKUP.get(layoutId);
if(localizedLayoutId > 0) {
final Object tag = view.getTag