设计模式:模板方法 编写自己的基类

建立自己的基类,减少代码冗余

public abstract class BaseActivity extends SwipeBackActivity {
    @Override
    protected final void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getArgs();
        setContentView(getLayoutId());
        initLayout();
        initData();
        initView();
        setListener();
    }

    /**
     * 模板方法,获取参数等操作
     */
    protected abstract void getArgs();

    /**
     * 模板方法:返回布局的id
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 模板方法:初始化布局(设置状态栏等)
     */
    protected abstract void initLayout();

    /**
     * 模板方法: 初始化布局
     */
    protected abstract void initView();

    /**
     * 模板方法: 初始化数据
     */
    protected abstract void initData();

    /**
     * 模板方法: 设置监听器
     */
    protected abstract void setListener();

    /**
     * 设置布局充满状态栏
     */
    protected void fullScreen() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明,否则导航栏会呈现系统默认的浅灰色
                Window window = getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用,表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                //导航栏颜色也可以正常设置
//                window.setNavigationBarColor(Color.TRANSPARENT);
            } else {
                Window window = getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
                attributes.flags |= flagTranslucentStatus;
//                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
    }

    //设置状态栏的颜色
    protected void setStatusBar(int colorId){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {  //设置状态栏
            getWindow().setStatusBarColor(getResources().getColor(colorId));//设置状态栏颜色
        }
    }
}
原文地址:https://www.cnblogs.com/zhaozilongcjiajia/p/11759388.html