开启DataBinding
首先我们要开启DataBinding,很早版本就开始支持了,所以一般来讲不用太担心。直接开。
android {
buildFeatures {
dataBinding true
}
}
使用DataBinding
页面中
其实和正常写页面没区别,就是在最外层加个< layout >标签,然后把原本最外层的配置放到layout里。这里没有使用DataBinding的数据绑定功能,想要绑定实体类做单向绑定或者双向绑定的话,还要再< layout>加个< Data>标签,我还用的不熟练后续我补充一下,个人最喜欢的还是免findviewbyid功能。
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</layout>
Activity中
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
super.onCreate(savedInstanceState);
}
Fragment中
private ViewDataBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater,R.layout.activity_main,container,false);
return binding.getRoot();
}
要注意的是Fragment的生命周期和Act是不一样的,多了几个,Fragment确认绘制页面是在onCreateView方法中,而这个方法在生命周期中是比onCreate()和构造方法都后的,所以如果在构造方法或者onCreate中使用binding会直接报空指针闪退。需要慎重考虑和设计!
封装
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
public abstract class BaseFragment extends Fragment {
private ViewDataBinding binding;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater,setLayoutId(),container,false);
setDataBinding(binding);
initView();
initListener();
return binding.getRoot();
}
protected abstract void initView();
protected abstract void initListener();
protected abstract int setLayoutId();
public void update(){}
protected abstract void setDataBinding(ViewDataBinding dataBinding);
public void back(Fragment fragment){
FragmentTransaction fragmentTransaction = getParentFragment().getChildFragmentManager().beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
}
}
|