Closed jotish closed 6 years ago
Refer mine. In a separate class.
`public class FragmentHelper {
public static FragmentManager getFragmentManager(Context context) {
return ((AppCompatActivity) context).getSupportFragmentManager();
}
public static void openFragment(Context context, int frameId, Fragment fragment) {
getFragmentManager(context).beginTransaction()
.replace(frameId, fragment, fragment.getClass().toString())
.addToBackStack(null).commit();
}
public static void addFragment(Context context, int frameId, Fragment fragment) {
getFragmentManager(context).beginTransaction()
.add(frameId, fragment, fragment.getClass().toString())
.addToBackStack(null).commit();
}
}`
thanks for your contribution @azizimusa but I think your helper class doesn't answer the question ( The class that you showed is a typical class to be reusable the fragment transactions. ).
"Most of the MVVM pattern examples, don't contain how to add/replace fragments from a ViewModel"
refers to how a ViewModel can handle this logic.
I understand it more like how to handle the Navigation using ViewModel?
First of all ViewModel responsibilities is to handle UI logic and actions (change to another fragment normally is an action). You already have a lot of options but the most common is to use navigator pattern to abstract the navigation logic or if you're using Arch Components you can use events or Navigator Component.
@erikcaffrey Thanks for the prompt answer. Totally agree that Navigation
architecture component is the right solution.
https://developer.android.com/topic/libraries/architecture/navigation/
Yeah! Maybe not the right solution for everything (it's a tool more to do an easy navigation) but if something in your architecture is working keep it working.
Totally agree with all of yours answer , but in navigation architecture we don't have an option to add fragment , it is handling only replace-fragment transaction what should I do in this case ?
@mrkamiali like I said before you can use Navigator Pattern a component (without the navigation component of architecture components) to abstract all your navigation logic. Something like https://github.com/android10/Android-CleanArchitecture-Kotlin/blob/master/app/src/main/kotlin/com/fernandocejas/sample/core/navigation/Navigator.kt
Most of the MVVM pattern examples, don't contain how to add/replace fragments from a ViewModel.