引言
本篇将介绍我最近在对
Android
项目进行开发时,对基类封装
的一些笔记分享。
Ui
BaseActivity
Activity 基类封装
open class BaseActivity : AppCompatActivity() {
private val viewModelProvideForActivity: ViewModelProvider by lazy { ViewModelProvider(this) }
fun <T : ViewModel> provideViewModel(type: Class<T>): T {
return viewModelProvideForActivity[type]
}
/* ======================== Lifecycle ======================== */
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
}
// ......
}
BaseFragment
Fragment 基类封装
相较于 BaseActivity,Fragment 的基础基类如下:
在获取上下文时,可通过重写 Fragment 的 onAttach 函数,对上下文进行获取并赋值,之后可通过 hostActivity 动态获取当前宿主Activity上下文;
由于 ViewModel 的特殊性,其生命周期观察者可为外层 Activity 或内部 Fragment,故对 ViewModelProvider 进行区分。
open class BaseFragment : Fragment() {
lateinit var hostActivity: AppCompatActivity
private val vpByActivity: ViewModelProvider by lazy { ViewModelProvider(hostActivity) }
private val vpByFragment: ViewModelProvider by lazy { ViewModelProvider(this) }
/* ======================== Logical Function ======================== */
fun <T : ViewModel> provideViewModelByActivity(type: Class<T>): T {
return vpByActivity[type]
}
fun <T : ViewModel> provideViewModelByFragment(type: Class<T>): T {
return vpByFragment[type]
}
/* ======================== Lifecycle ======================== */
override fun onAttach(context: Context) {
super.onAttach(context)
hostActivity = context as AppCompatActivity
}
}