基本實現(xiàn)已經完成了蚯斯,接下來就是封裝了况鸣。
一牢贸、Acitvity的封裝
我把Activity封裝成了三層
1.MvvmActivity
public abstract class MvvmActivity<V extends ViewDataBinding, VM extends ViewModel> extends AppCompatActivity {
/**
* DataBinding
*/
protected V mDataBinding;
/**
* ViewModel
*/
protected VM mViewModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initAAC();
}
/**
* 獲取視圖ID
*
* @return 視圖ID
*/
protected abstract int getLayoutId();
/**
* 獲取ViewModel
*
* @return ViewModel
*/
protected abstract VM getViewModel();
/**
* 初始化 DataBinding 變量ID 和 變量實體類 Map
*
* @return DataBinding 變量SparseArray
*/
protected abstract SparseArray<Object> getVariableSparseArray();
/**
* 初始化AAC組件
*/
private void initAAC() {
mDataBinding = DataBindingUtil.setContentView(this, getLayoutId());
mViewModel = getViewModel();
final SparseArray<Object> variableSA = getVariableSparseArray();
if (variableSA != null && variableSA.size() > 0) {
for (int i = 0; i < variableSA.size(); ++i) {
final int variableId = variableSA.keyAt(i);
final Object variableValue = variableSA.valueAt(i);
mDataBinding.setVariable(variableId, variableValue);
}
}
//讓ViewModel擁有View的生命周期感應
if (mViewModel != null) {
getLifecycle().addObserver(mViewModel);
}
}
/**
* 工廠模式創(chuàng)建ViewModel
*
* @param cls Activity Class
* @param factory 工廠
* @return ViewModel子類
*/
public VM createViewModel(@NonNull Class<VM> cls, @NonNull ViewModelProvider.NewInstanceFactory factory) {
return new ViewModelProvider(this, factory).get(cls);
}
@Override
protected void onDestroy() {
super.onDestroy();
//銷毀DataBinding
if (mDataBinding != null) {
mDataBinding.unbind();
}
}
}
第一層把databinding進行綁定和解綁,給ViewModel注冊生命周期感知
2.MvvmActivity
public abstract class MvvmBaseActivity<V extends ViewDataBinding, VM extends ViewModel> extends MvvmActivity<V, VM> {
/**
* RxPermission (響應式權限申請框架)
*/
protected RxPermissions mRxPermissions;
/**
* 頁面跳轉攜帶的數(shù)據(jù)Bundle
*/
protected Bundle mBundle;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initParam();
initData();
initAction();
initObserver();
}
/**
* 初始化參數(shù)
*/
protected void initParam() {
if (getIntent() != null) {
mBundle = getIntent().getExtras();
}
}
/**
* 初始化數(shù)據(jù)
*/
protected void initData() {
//創(chuàng)建RxPermission對象
if (this.getClass().isAnnotationPresent(NeedPermissions.class)) {
mRxPermissions = new RxPermissions(this);
}
//注冊EventBus
if (this.getClass().isAnnotationPresent(BindEventBus.class)
&& !EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
}
/**
* 初始化事件
*/
protected void initAction() {
}
/**
* 初始化 LiveData Observer
*/
protected void initObserver() {
//顯示加載中提示對話框
mViewModel.getUiChangeLiveDataManager().getShowLoadingDialogEvent().observe(this, s -> {
LoadingDialog.getInstance()
.setHintText(s)
.show(this);
});
//隱藏加載中提示對話框
mViewModel.getUiChangeLiveDataManager().getHideLoadingDialogEvent().observe(this, o -> {
LoadingDialog.getInstance().hide();
});
//切換Activity
mViewModel.getUiChangeLiveDataManager().getStartActivityEvent().observe(this, paramSA -> {
final Class<?> cls = (Class<?>) paramSA.get(BaseViewModel.ParamConstant.CLASS);
final Bundle bundle = (Bundle) paramSA.get(BaseViewModel.ParamConstant.BUNDLE);
final Integer requestCode = (Integer) paramSA.get(BaseViewModel.ParamConstant.REQUEST_CODE);
if (requestCode == null) {
startActivity(cls, bundle);
} else {
startActivityForResult(cls, bundle, requestCode);
}
});
//關閉銷毀Activity
mViewModel.getUiChangeLiveDataManager().getFinishEvent().observe(this, o -> {
finish();
});
}
/**
* 通過Class跳轉界面
**/
public void startActivity(Class<?> cls) {
startActivity(cls, null);
}
/**
* 含有Bundle通過Class跳轉界面
**/
public void startActivity(Class<?> cls, Bundle bundle) {
Intent intent = new Intent();
intent.setClass(this, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivity(intent);
}
/**
* 通過Class跳轉界面
**/
public void startActivityForResult(Class<?> cls, int requestCode) {
startActivityForResult(cls, null, requestCode);
}
/**
* 含有Bundle通過Class跳轉界面
**/
public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
Intent intent = new Intent();
intent.setClass(this, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivityForResult(intent, requestCode);
}
@Override
protected void onDestroy() {
super.onDestroy();
//銷毀加載中Dialog
LoadingDialog.getInstance().destory();
//銷毀權限申請框架
mRxPermissions = null;
//清空Disposable
clearDisposable();
//解注冊EventBus
if (this.getClass().isAnnotationPresent(BindEventBus.class)
&& EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
}
}
第二層封裝了一些通用的方法和一些必須框架的綁定和解綁
3.MvvmBaseActivity
public abstract class AppBaseActivity<V extends ViewDataBinding, VM extends ViewModel> extends MvvmBaseActivity<V, VM> {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogUtil.d("頁面", this.getClass().getSimpleName());
}
@Override
protected void onStart() {
super.onStart();
initStatusBar();
}
/**
* 初始化數(shù)據(jù)
*/
@Override
protected void initData() {
super.initData();
//Activity默認背景為白色
getContentView().setBackgroundResource(R.color._FFFFFF);
//設置狀態(tài)欄高度
if (!isSetCustomStatusBarHeight()) {
@IdRes final int id = ResourceUtil.getResId("rl_layout_title_bar", R.id.class);
if (id != -1) {
final View view = findViewById(id);
if (view != null) {
view.setPadding(0, StatusBarUtil.getStatusBarHeight(this), 0, 0);
}
}
}
}
/**
* 初始化狀態(tài)欄
*/
private void initStatusBar() {
//設置默認狀態(tài)欄背景顏色 為透明色
StatusBarUtil.setStatusBarColor(this, R.color._00000000);
//設置默認狀態(tài)欄字體顏色 為淺色
StatusBarUtil.setStatusBarContentColor(this, isSetStatusBarContentDark());
}
/**
* 是否自定義設置狀態(tài)欄高度
*
* @return true 自定義設置 false 默認設置
*/
protected boolean isSetCustomStatusBarHeight() {
return false;
}
/**
* 是否設置狀態(tài)欄內容顏色為深色
*
* @return true 深色 false 淺色
*/
protected boolean isSetStatusBarContentDark() {
return false;
}
/**
* 連續(xù)雙擊退出應用
*/
protected boolean mExitApp;
/**
* 指定間隔時間內 按下兩次返回鍵退出App
*/
public void doubleDownExitApp() {
if (mExitApp) {
//關閉所有的Activity
ActivityUtils.finishAllActivities();
} else {
mExitApp = true;
ToastUtils.showShort("再按一次退出應用");
//超過兩秒沒有再次點擊懒闷,則不退出App
new Handler().postDelayed(() -> mExitApp = false, 2000);
}
}
}
第三層封裝了一些沉浸式狀態(tài)欄和雙擊退出的一些方法
以上利用泛型限制了數(shù)據(jù)類型十减,利用了抽象方法讓子類實現(xiàn)變化的部分。
二愤估、改造后的DemoActivity
public class DemoActivity extends AppBaseActivity<ActivityDemoBinding, AClass> {
@Override
protected int getLayoutId() {
return R.layout.activity_demo;
}
@Override
protected AClass getViewModel() {
return new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(AClass.class);
}
@Override
protected SparseArray<Object> getVariableSparseArray() {
SparseArray<Object> variableSA = new SparseArray<>();
variableSA.put(aClass, mViewModel);
return variableSA;
}
}