Bottom Navigation View With Fragments (No fragment re-creation).
Solving the problem of always creating fragment new instance
What is a fragment ?
A Fragment is a piece of an activity which enable more modular activity design. Its can be said to be a sub-activity.
Multiple fragments can be used in a single activity, each fragment has it own layout and life-cycle. Learn more about fragment on google android developer guide page. follow link below.
Using fragments was cool until i tried applying it to bottom navigation view. Each time i navigate to another fragment, when i returned back to the previous one, the fragment was re-created.
what if someone scrolled to the 70th item in the recycler view, navigates then navigates back ?
The fragment will be re-created, and the user will have to scroll once again to the 70th item. I don’t think i want to start messing with bundles and back stack problems
So i created a new project
After a successful build, i created 3 new fragments.
- Home Fragment (Inflated a recycler view in it)
- Dashboard Fragment (Contains a button an a textview)
- Notifications Fragment (Contains scrollable text)
Note: I did not include fragment factory methods and interface callbacks, when creating the fragments.
I wanted to use toolbar, and customize the activity_main.xml UI to make it a little flexible, so i edited my styles.xml and activity_main.xml file.
To inflate the fragments in a frame layout, i had to inflate a content_main.xml layout file.
You can clone the project on github
After many search for the best way to solve the problem, i finally came up with a solution that works perfectly. In the main activity class, i created five global objects, and set the Home Fragment as the active fragment.
In onCreate, after setContentView, i hid two fragments and committed them to the fragment manager, but i didn't hide the first fragment that will serve as home.
To move between activities, i customized the BottomNavigationView.OnNavigationItemSelectedListener method to hide the active fragment, commit it, then set the current fragment as the active fragment and it works perfectly.
I also included an options menu to launch a new settings activity.
Note: to prevent the Activity from recreating itself when the back button is clicked, you have to make the launchMode your “fragment hosting class” or MainActivity.java class singleTop.
I customized each fragment. clone the project to see full code. The main solution is posted above already.
NOTE
- The fragments retain their positions, even after i launched a new activity and went back.
- Screen orientation is set to portrait in the manifest file.
- This is just a quick work around, see link below for the official solution.
Hope this helps.
Thanks.
UPDATE !!!
Refer to this for the official solution.
https://github.com/android/architecture-components-samples/tree/master/NavigationAdvancedSample