This logic can be moved to ViewModel
, with a bit of overhead though. For sure, the decision of which fragment to add should be moved to ViewModel
, but the adding fragment's code should stay in Fragment
(or Activity
). I think it should look something like this:
Fragment:
override fun onItemClick(titleName: Int) {
viewModel.onTitleClick(titleName)
}
ViewModel:
fun onTitleClick(titleName: Int) {
when (titleName) {
R.string.about_terms_service -> {
postViewModelEvent(ShowWebViewFragmentEvent())
}
R.string.about_open_source_licenses -> {
// TODO: open License fragment
}
}
}
In the ViewModel
you should replace this // TODO
s with a specific command to your View (Fragment
, Activity
), which will trigger navigating to specific fragment. On how to do that, for example, is written here (but of course, any ViewModel
- Fragment
solution will work).
In this case, this logic can be easily tested.
If you're connecting your ViewModel
with your Fragment
via view model events (described in the link), you can do this:
Create an event of showing WebViewFragment
like this:
class ShowWebViewFragmentEvent(): ViewModelEvent {
override fun handle(activity: BaseActivity) {
super.handle(activity)
activity?.addFragment(
WebViewFragment.newInstance(
TERMS_LINK,
getString(R.string.about_terms_service)
)
)
}
}
and post it in your ViewModel
(replacing first // TODO
) like this:
postViewModelEvent(ShowWebViewFragmentEvent())
Please note, that all the required changes from the linked post should be done.