I am new to Android programming though I am coding in another languages. I am not able to navigate to home fragment in a particular scenario.
I have three fragments among few more viz., Settings, Capacity and About. All these can be reached via Overflow Toolbar menu items. Settings can be reached thru another button on home fragment.
Use case 1: Click Settings button on home fragment. Settings open. In Settings use either Up/Home or Back Button. On clicking any one of them, home fragment is reached.
Use case 2: Click Toolbar overflow menu(three dots). Three menu item appears. Select Settings menu item. Settings Open. In Settings, use either Up/Home or Back Button. On clicking any one of them, home fragment is reached.
Use Case 1 is working fine. I think nav_graph defined is used here where navigation between fragments is defined.
Use Case 2 fails. Upon pressing Up/Home button or Back button, I get white screen rather landing on home fragment.
I studied code in several websites including SO and official Android site. But could not make out what kind of code to be used when navigating back to home fragment from another fragment(which was particularly reached via Toolbar menu and outside of nav_graph).
I studied methods in stack in debug window. But did not help me either.
Please enlighten me the approach to be used.
CodePudding user response:
First set Home Fragment in content view(frame view). on top you can your next fragment kinda stack of fragments 1 above another. create method in activity this method will popout all fragments except Home Fragment.
Add Fragment use below code
Fragment fragment = new FragmentHome();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).addToBackStack(fragment.getClass().getSimpleName()).commit();
To go Home clearing all
public void goToHome()
{
FragmentManager fragmentManager = getSupportFragmentManager();
for(int i = 0; i < fragmentManager.getBackStackEntryCount()-1; i)
{
fragmentManager.popBackStack();
}
}
CodePudding user response:
I continued searching for solution to my problem. I came across a solution in https://medium.com/mobile-app-development-publication/learn-android-navigation-component-through-coding-79dc47b240b3
It worked perfectly well and solved white screen issue and also not using explicit method using fragment manager for traversing to another fragment. It was about linking menu items to navigation graph.