I have three fragments and all of them have two functions which are EXACTLY THE SAME. My problem is that I (obviously) don't want to copy the same two functions over and over again and put it in the fragments.
Ain't there a way to put these functions in one place and call them from my fragments? These functions have to do with navController and Toolbar Navigation so I cant put it in my viewmodel. Another solution could be to create a Baseclass fragment, put these functions in there and inherit from it?
private fun initProgressbar(currentStateNumber: StateProgressBar.StateNumber, progressBarDescription: ArrayList<String>) =
state_progress_bar.apply {
setStateDescriptionData(progressBarDescription)
setCurrentStateNumber(currentStateNumber)
}
private fun initToolbar(navController: NavController, appBarConf: AppBarConfiguration, textToolbar: String?) =
toolbar.apply {
setupWithNavController(navController, appBarConf)
toolbar_title.text = textToolbar
}
I didn't found any solution without violating the mvvm architecture or the lifecyle of the fragments. I am using jetpack navigation, mvvm and dagger hilt.
I appreciate every help.
abstract class BaseFragment(
layout: Int,
private val progressBarDescription: ArrayList<String>,
private val stateNumber: StateProgressBar.StateNumber
) : Fragment(layout) {
private val _navController: NavController by lazy { findNavController() }
private val appBarConf by lazy { AppBarConfiguration(_navController.graph) }
private val calibrateRepairToolbarText by lazy { arguments?.getString("calibrate_repair_toolbar_text") }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initProgressbar()
initToolbar()
}
val navController: NavController
get() = _navController
fun initProgressbar(): StateProgressBar = state_progress_bar.apply {
setStateDescriptionData(progressBarDescription)
setCurrentStateNumber(stateNumber)
}
fun initToolbar(): MaterialToolbar = toolbar.apply {
setupWithNavController(_navController, appBarConf)
toolbar_title.text = calibrateRepairToolbarText
}
}
And then in the other Fragment:
class Fragment(
private val progressBarDescription: ArrayList<String>,
@StateNumberOne private val stateNumber: StateProgressBar.StateNumber
) : BaseFragment(
R.layout.fragment_calibrate_repair_message,
progressBarDescription,
stateNumber
) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
}
You can create a baseFragment, with these methods, and then have your three Fragments extend baseFragment