Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android封装BaseActivity

详解Android封装一个全局的BaseActivity

作者:还吹着风、

这篇文章主要介绍了详解Android封装一个全局的BaseActivity,对封装感兴趣的同学,可以参考下

1.前言

2.特点

3.代码及说明

3.1.优缺点

下面会讨论哪些代码应该放在BaseActivity里面,哪些需要谨慎

3.2.代码

下面我贴一份我自己封装的BaseActivity,在代码中和代码下面做了解释:

public abstract class BaseActivity extends AppCompatActivity {

    public Activity mActivity;
    private Unbinder mUnbinder;
    private static float sNoncompatDensity;
    private static float sNoncompatScaledDensity;
    private MaterialDialog mDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onAdjustLayout();
        setContentView(setContentLayout());
        //这里的是初始化绑定ButterKnife,在onDestory做了销毁
        mUnbinder = ButterKnife.bind(this);
        this.mActivity = this;
        //统一将一个activity添加到一个集合里面
        AppManager.getInstance().addActivity(mActivity);
        initToolBar();
        initPresenter();
        initData(savedInstanceState);
        Log.e("app", this.getClass().getSimpleName() + "------onCreate");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e("app", this.getClass().getSimpleName() + "------onStart");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.e("app", this.getClass().getSimpleName() + "------onRestoreInstanceState");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e("app", this.getClass().getSimpleName() + "------onRestart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("app", this.getClass().getSimpleName() + "------onResume");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.e("app", this.getClass().getSimpleName() + "------onSaveInstanceState");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("app", this.getClass().getSimpleName() + "------onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e("app", this.getClass().getSimpleName() + "------onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        onDestroyActivity();
        mUnbinder.unbind();
        Log.e("app", this.getClass().getSimpleName() + "------onDestroy");
    }

    /**
     * 显示一个Fragment
     */
    public void showFragment(Fragment fragment) {
        if (fragment != null && fragment.isHidden()) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.show(fragment);
            fragmentTransaction.commit();
        }
    }

    /**
     * 隐藏一个Fragment
     */
    public void hideFragment(Fragment fragment) {
        if (fragment != null && !fragment.isHidden()) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.hide(fragment);
            fragmentTransaction.commit();
        }
    }

	//这是一个设置toolbar标题栏的方法,ToolBarOptions类主要是持有一些id
    public void setToolBar(int toolBarId, ToolBarOptions options) {
        Toolbar toolbar = findViewById(toolBarId);
        if (options.titleId != 0) {
            toolbar.setTitle(options.titleId);
        } else {
            toolbar.setTitle("");
        }
        if (!TextUtils.isEmpty(options.titleString)) {
            toolbar.setTitle(options.titleString);
        }
        if (options.backgroundColor != 0) {
            toolbar.setBackgroundResource(options.backgroundColor);
        }
        if (options.logoId != 0) {
            toolbar.setLogo(options.logoId);
        }
        setSupportActionBar(toolbar);

        if (options.isNeedNavigate) {
            toolbar.setNavigationIcon(options.navigateId);
            toolbar.setContentInsetStartWithNavigation(0);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!AppUtils.isNotFastClick()) {
                        return;
                    }
                    onNavigateUpClicked();
                }
            });
        }
    }

	//子类直接调用展示toast
    public void showToast(String s) {
        ToastUtil.showToast(this, s);
    }

	//给子类提供一个获取activity对象的方式
    public Activity getActivity() {
        return this;
    }

	//一个弹窗loading库 github地址:
    //implementation 'com.afollestad.material-dialogs:core:0.9.6.0'
    public void showLoading(String loadDesc) {
        mDialog = new MaterialDialog.Builder(this)
                .progress(true, -1)
                .content(loadDesc)
                .canceledOnTouchOutside(false)
                .cancelable(false)
                .show();
    }

    public void showLoading(int resId) {
        mDialog = new MaterialDialog.Builder(this)
                .progress(true, -1)
                .content(getString(resId))
                .canceledOnTouchOutside(false)
                .cancelable(false)
                .show();
    }

    public void showLoading() {
        mDialog = new MaterialDialog.Builder(this)
                .progress(true, -1)
                .content("加载中...")
                .canceledOnTouchOutside(false)
                .cancelable(false)
                .show();
    }

    public void hideLoading() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

	//这里是退出app相关的逻辑,可以根据自己的退出做具体的处理
    public void exitLogin() {
        SharedPreferenceUtils.getInstance(mActivity).put(Constant.KEY_LOGIN_TOKEN, "");
        if (mDialog != null) {
            mDialog.hide();
            mDialog = null;
        }
        mDialog = new MaterialDialog.Builder(this)
                .canceledOnTouchOutside(false)
                .title("提示")
                .content("账号已在其他地方登录,请退出重新登录!")
                .positiveText("确定")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        AppManager.getInstance().finishAllActivity();
                        Intent intent = new Intent(mActivity, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }).show();
    }

    private void onNavigateUpClicked() {
        onBackPressed();
    }

    //开始contentLayout前调整布局(子类若有需要可以单独复写)
    public void onAdjustLayout() {

    }

	//下面这5个方法是子类必须实现的,分别是layout布局、toolbar、mvp的persenter初始化、
	//onCreate内的initData、以及页面销毁的onDestroyActivity(可以根据自己的需要添加)
    public abstract int setContentLayout();

    public abstract void initToolBar();

    public abstract void initPresenter();

    public abstract void initData(Bundle savedInstanceState);

    public abstract void onDestroyActivity();
}

3.3.注意点

4.总结

不是很复杂,写的也比较详细,也基本适用于绝大部分的场景。可能还有其他需要注意的细节回头想起来再补上。

以上就是详解Android封装一个全局的BaseActivity的详细内容,更多关于Android封装BaseActivity的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文