public abstract class BaseFragment<T extends ViewBinding> extends Fragment {
public static final String TAG = "BaseFragment";
protected FragmentActivity mActivity;
protected T binding; // 泛型绑定类
private boolean isLoaded = false;
@Override
public void onAttach(@NotNull Context context) {
super.onAttach(context);
mActivity = getActivity();
}
@Nullable
@Override
public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = createViewBinding(inflater, container); // 创建绑定类实例
initData(getArguments());
initView();
return binding.getRoot(); // 返回根视图
}
// 创建视图绑定的抽象方法
protected abstract T createViewBinding(LayoutInflater inflater, ViewGroup container);
protected void initData(Bundle arguments) {
}
protected abstract void initView();
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume");
if (!isLoaded) {
onLazyLoad();
Log.d(TAG, this + "lazyInit:!!!!!!!");
isLoaded = true;
}
}
protected void onLazyLoad() {
}
@Override
public void onDestroy() {
super.onDestroy();
isLoaded = false;
}
}
使用方式
build.gradle文件添加支持dataBinding
dataBinding {
enabled = true
}
重写 createViewBinding()绑定布局文件.xml
public class VojsLiveCoverFragment extends BaseFragment<VojsliveCoverFragmentBinding> {
public static final String TAG = "VojsLiveCoverFragment";
@Override
protected VojsliveCoverFragmentBinding createViewBinding(LayoutInflater inflater, ViewGroup container) {
return VojsliveCoverFragmentBinding.inflate(inflater, container, false);
}
public static VojsLiveCoverFragment newInstance(VojsLJBean vojsLJBean) {
VojsLiveCoverFragment fragment = new VojsLiveCoverFragment();
Bundle args = new Bundle();
args.putSerializable(VOJS_LJ_BEAN, vojsLJBean);
fragment.setArguments(args);
return fragment;
}
@Override
protected void initView() {
Glide.with(getContext()).load("URL").into(binding.blurCoverImageView);
}
}