Kt 封装BaseActivity

嘿,今天的你过的还好吗

用Kt好久了,也就没系统的改一些什么东西,今天就封装一下Activity..以备以后使用

package com.xql.shopping.base

import android.app.Activity
import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProvider.NewInstanceFactory
import com.blankj.utilcode.util.ToastUtils
import com.xql.loading.LoadingDialog
import com.xql.shopping.viewmodel.BaseViewModel
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import java.lang.reflect.ParameterizedType

/**
 *
 * @ClassName: BaseActivity
 * @Description: BaseActivity
 * @CreateDate: 2021/7/17 8:06
 * @UpdateUser: RyanLiu
 */
abstract class BaseActivity : AppCompatActivity() {
    protected final var TAG: String = "sansuiban";

    //等待窗对象
    private var loadingDialog: LoadingDialog? = null
    var mBinding: B? = null;
    var mViewModel: VM? = null;

    //是否显示标题栏
    private var isShowTitle: Boolean? = false;

    //是否显示状态栏
    private var isShowStatusBar: Boolean? = false;

    //是否允许旋转屏幕
    private var isAllowScreenRoate: Boolean? = true;
    var context: Context? = null;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context = this;
        //activity管理
        ActivityCollector().addActivity(this)
        if (!isShowTitle!!) {
            requestWindowFeature(Window.FEATURE_NO_TITLE)
        }
        if (!isShowStatusBar!!) {
            window.setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
            );
        }
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//        如果>=4.4才支持沉浸式
//        显示上面的导航栏
//                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        显示下面的导航键
//                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//        隐藏状态栏
//                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        显示状态栏
//                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//                }
        //设置屏幕是否可旋转
        if (!isAllowScreenRoate!!) {
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        } else {
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        }

        //初始化布局
        mBinding = DataBindingUtil.setContentView(this, layoutId());
        mBinding?.lifecycleOwner = (this)
        initDialog();
        //创建我们的ViewModel。
        createViewModel()
        //初始化控件
        initView()
        //设置数据
        initData()
    }

    /**
     * 绑定viewmodel
     */
    open fun createViewModel() {
        if (mViewModel == null) {
            val modelClass: Class<*>
            val type = javaClass.genericSuperclass
            if (type is ParameterizedType) {
                modelClass = type.actualTypeArguments[1] as Class<*>
                Log.i(TAG, "createViewModel: $modelClass")
            } else {
                //如果没有指定泛型参数,则默认使用BaseViewModel
                modelClass = BaseViewModel::class.java
            }
            mViewModel =
                ViewModelProvider(
                    this,
                    NewInstanceFactory()
                ).get(modelClass as Class) as VM
        }
    }

    /**
     * 初始化各种Dialog
     */
    private fun initDialog() {
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog(this);
        }
    }

    /**
     * 显示等待Dialog
     */
    open fun showLoading() {
        if (loadingDialog != null && !loadingDialog!!.isShowing) loadingDialog!!.show()
    }

    /**
     * 隐藏等待Dialog
     */
    open fun hideLoading() {
        if (loadingDialog != null && loadingDialog!!.isShowing) {
            loadingDialog!!.dismiss()
        }
    }

    /**
     * 显示等待Dialog,可自定义显示内容
     */
    open fun showLoading(msg: String?): LoadingDialog? {
        if (loadingDialog != null && !loadingDialog!!.isShowing) loadingDialog!!.setMessage(msg)
            ?.show()
        return loadingDialog
    }


    /**
     * 初始化布局
     *
     * @return 布局id
     */
    protected abstract fun layoutId(): Int

    /**
     * 初始化控件
     */
    protected abstract fun initView()

    /**
     * 设置数据
     */
    protected abstract fun initData()

    /**
     * 设置是否显示标题栏
     *
     * @param showTitle true or false
     */
    open fun setShowTitle(showTitle: Boolean) {
        isShowTitle = showTitle
    }

    /**
     * 设置是否显示状态栏
     *
     * @param showStatusBar true or false
     */
    open fun setShowStatusBar(showStatusBar: Boolean) {
        isShowStatusBar = showStatusBar
    }

    /**
     * 是否允许屏幕旋转
     *
     * @param allowScreenRoate true or false
     */
    open fun setAllowScreenRoate(allowScreenRoate: Boolean) {
        isAllowScreenRoate = allowScreenRoate
    }


    /**
     * 保证同一按钮在1秒内只会响应一次点击事件
     */
    abstract class OnSingleClickListener : View.OnClickListener {
        private var lastClickTime: Long = 0
        abstract fun onSingleClick(view: View?)
        override fun onClick(view: View) {
            val curClickTime = System.currentTimeMillis()
            if (curClickTime - lastClickTime >= MIN_CLICK_DELAY_TIME) {
                lastClickTime = curClickTime
                onSingleClick(view)
            }
        }

        companion object {
            //两次点击按钮之间的间隔,目前为1000ms
            private const val MIN_CLICK_DELAY_TIME = 1000
        }
    }

    /**
     * 同一按钮在短时间内可重复响应点击事件
     */
    abstract class OnMultiClickListener : View.OnClickListener {
        abstract fun onMultiClick(view: View?)
        override fun onClick(v: View) {
            onMultiClick(v)
        }
    }

    /**
     * 活动管理器
     */
    class ActivityCollector() {
        var activitys: MutableList = ArrayList();

        /**
         * 向list中添加一个活动
         *
         * @param activity 活动
         */
        fun addActivity(activity: Activity) {
            activitys.add(activity);
        }

        /**
         * 从List中移除活动
         *
         * @param activity 活动
         */
        fun removeActivity(activity: Activity) {
            activitys.remove(activity);
        }

        /**
         * 将List中储存的活动全部销毁掉
         */
        fun finishAll() {
            for (acitvity: Activity in activitys) {
                if (!acitvity.isFinishing()) {
                    acitvity.finish();
                }
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        //activity管理
        ActivityCollector().removeActivity(this);
    }

    override fun onResume() {
        super.onResume()
        AndPermission.with(context).runtime()
            .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
            .onDenied({
                ToastUtils.showLong("权限获取失败,将退出应用");
                ActivityCollector().finishAll();
            }).onGranted({
            }).start();
    }

}

没更新或者频繁更新的时候都是在认真生活

你可能感兴趣的:(Kt 封装BaseActivity)