这个内置的demo用了navigation作为路由工具
navigation的出栈会让下个 fragment重新调用onVIewCreated
所以可以通过在fragment中持有一个实例 来复用view 从而做到防止页面重置
abstract class BaseFragment<VB : ViewBinding> : Fragment() {
lateinit var viewBinding: VB
private var initView: View? = null
private var hasInit = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return if (initView != null) {
hasInit = true
initView!!
} else {
viewBinding = inflateViewBinding(inflater, container)
initView = viewBinding.root
initView!!
}
}
@CallSuper
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (!hasInit) {
// 以下代码块 只初始化一次
hasInit = true
initView()
registerListener()
}
// 数据的回调无论何时都需监听
// navigation 的出栈会让下个 fragment 重新调用 onViewCreated
registerObserver()
}
abstract fun inflateViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB
abstract fun initView()
abstract fun registerListener()
abstract fun registerObserver()
}