puzhibing
2026-08-21 5fa94b3718b4a78a4fcea4c97652b0ef20b7de3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package com.xw.common.base
 
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.blankj.utilcode.util.BarUtils
import com.xw.common.R
import com.xw.common.utils.AppGlobals
import com.xw.common.utils.BindUtils.enableBindingLogging
import com.xw.common.utils.ScreenAdaptationUtil
import java.lang.reflect.ParameterizedType
 
abstract class BaseActivity<V : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() {
 
    var TAG = "zmc-${this.javaClass.simpleName}"
 
    lateinit var viewModel: VM
    lateinit var binding: V
 
    private var dialog: LoadingDialog? = null
 
    @SuppressLint("SourceLockedOrientationActivity")
    override fun onCreate(savedInstanceState: Bundle?) {
        ScreenAdaptationUtil.setCustomDensity(this, AppGlobals.getApplication())
        BarUtils.transparentStatusBar(this)
        BarUtils.setStatusBarLightMode(this, true)
        //统一设置activity竖屏
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        super.onCreate(savedInstanceState)
 
        // 在 setContentView 之前强制设置
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
 
        // 或者同时设置多个模式
        window.setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN or
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
        )
        window.addFlags(
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED //锁屏状态下显示
                    or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD //解锁
                    or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON //保持屏幕长亮
                    or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON //打开屏幕
        )
 
        initDataBinding()
        applyNavigationBarPadding()// 处理底部导航栏适配
        initViewModel()
        initUiObservable()
        myCreate(savedInstanceState)
        initData()
        setListener()
        setObservable()
        init()
 
        // 在 Activity 中使用 OnBackPressedDispatcher
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                onBackPressedHandel()
            }
        })
    }
 
    /**
     * 自动适配底部导航栏/手势条高度
     * 给根视图添加底部内边距,避免内容被遮挡
     */
    protected open fun applyNavigationBarPadding() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { view, windowInsets ->
            val insets = windowInsets.getInsets(WindowInsetsCompat.Type.navigationBars())
            onApplyNavigationBarInsets(view, insets.bottom)
            WindowInsetsCompat.CONSUMED
        }
    }
    /**
     * 子类可覆盖此方法自定义底部内边距处理
     * @param bottomInset 底部导航栏/手势条高度(像素)
     */
    protected open fun onApplyNavigationBarInsets(view: View, bottomInset: Int) {
        view.updatePadding(bottom = bottomInset)
    }
 
    open fun onBackPressedHandel() {
        // 处理返回事件,使用 OnBackPressedDispatcher 替代已弃用的 onBackPressed 方法
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        if (null != currentFocus) imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0) //隐藏软键盘
        overridePendingTransition(R.anim.activity_close_open, R.anim.activity_close_exit)
        finish()
    }
 
    /**
     * 创建dataBingding,并自动设置布局
     */
    private fun initDataBinding() {
        val dbClass = genericTypeBinding()
        val method = dbClass.getMethod("inflate", LayoutInflater::class.java)
        binding = method.invoke(null, layoutInflater) as V
        setContentView(binding.root)
        binding.enableBindingLogging()
    }
 
    private fun initViewModel() {
        viewModel = createViewModel()
        binding.setVariable(getBindingVariable(), viewModel)
        binding.lifecycleOwner = this
 
        //让ViewModel拥有View的生命周期感应
        lifecycle.addObserver(viewModel)
    }
 
    private fun initUiObservable() {
        viewModel.dialogEvent.observe(this) {
            if (it == "dismiss") {
                dismissDialog()
            } else {
                showDialog(it)
            }
        }
        viewModel.onBackEvent.observe(this) {
            if (it == "back") {
                onBackPressed()
            } else if (it == "finish") {
                finish()
            }
        }
        viewModel.closeEvent.observe(this) {
            if (it == "close") {
                closeKeyboard()
            } else if (it == "hide") {
                hideKeyboard()
            }
        }
        viewModel.startActivityEvent.observe(this) { params ->
            val clz = params["CLASS"] as Class<*>
            var bundle: Bundle? = null
            try {
                bundle = params["BUNDLE"] as Bundle
            } catch (e: Exception) {
 
            }
            if (params["requestCode"] == null) {
                startActivity(clz, bundle)
                return@observe
            }
            val mIntent = Intent(this@BaseActivity, clz)
            bundle?.let {
                mIntent.putExtras(it)
            }
            startActivityForResult(mIntent, params["requestCode"] as Int)
            overridePendingTransition(R.anim.activity_open_enter, R.anim.activity_open_exit)
        }
    }
 
    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this).get(genericTypeViewModel())
    }
 
    /**
     * 获取当前类泛型viewmodel的Class类型
     * @return
     */
    private fun genericTypeViewModel(): Class<VM> {
        return (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[1] as Class<VM>
    }
 
    private fun genericTypeBinding(): Class<V> {
        return (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<V>
    }
 
 
    open fun setListener() {}
 
    open fun setObservable() {}
 
    open fun myCreate(savedInstanceState: Bundle?) {}
 
    open fun initData() {}
 
    open fun init() {}
 
    /** 获取参数Variable */
    protected abstract fun getBindingVariable(): Int
 
    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    fun startActivity(clz: Class<*>?, bundle: Bundle? = null) {
        val intent = Intent(this, clz)
        bundle?.let {
            intent.putExtras(it)
        }
        startActivity(intent)
        overridePendingTransition(R.anim.activity_open_enter, R.anim.activity_open_exit)
    }
 
    fun startActivityForResult(clz: Class<*>?, code: Int, bundle: Bundle? = null) {
        val intent = Intent(this, clz)
        bundle?.let {
            intent.putExtras(it)
        }
        startActivityForResult(intent, code)
        overridePendingTransition(R.anim.activity_open_enter, R.anim.activity_open_exit)
    }
 
    var inputMethodManager: InputMethodManager? = null
 
    open fun closeKeyboard() {
        if (window.attributes.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (currentFocus != null) {
                if (inputMethodManager == null) {
                    inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                }
                inputMethodManager?.hideSoftInputFromWindow(
                    currentFocus!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS
                )
            }
        }
    }
 
    private fun hideKeyboard() {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
    }
 
    // 关闭默认局部刷新动画
    fun closeRvAnim(rv: RecyclerView) {
        rv.itemAnimator?.addDuration = 0
        rv.itemAnimator?.changeDuration = 0
        rv.itemAnimator?.moveDuration = 0
        rv.itemAnimator?.removeDuration = 0
        (rv.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
    }
 
    fun showDialog(title: String = "加载中...") {
        if (isFinishing) {
            return
        }
        if (dialog != null) {
            dialog!!.show(title)
        } else {
            dialog = LoadingDialog(this)
            dialog!!.show(title)
        }
    }
 
    fun dismissDialog() {
        if (dialog != null && dialog!!.isShowing) {
            dialog!!.dismiss()
        }
    }
}