Im creating a app with three sections home,color,profile I'm using bottom navigation view with fragments to achieve this.
App UI Here is my code: Main Activity on create method:
final HomeFragment homeFragment = new HomeFragment();
final ColorFragment colorFragment = new ColorFragment();
final ProfileFragment profileFragment = new ProfileFragment();
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment active = homeFragment;
switch (item.getItemId()){
case R.id.action_home:
active = homeFragment;
break;
//return true;
case R.id.action_color:
active = colorFragment;
break;
case R.id.action_profile:
active = profileFragment;
break;
default:
active = homeFragment;
break;
}
//Loading the fragment on click
fragmentManager.beginTransaction().replace(R.id.fragment_container,active).commit();
return true;
}
});
Im using fragment manager to load the fragment in my Main Activity which comes with below problem.
1.It reloads the fragment each time I click on the bottom navigation icon.(Im getting data from firebase this will be costly )
I have read many articles regarding this,i found solutions like below:
- Using hiding the fragments on creation of activity
fragmentManager.beginTransaction().add(R.id.fragment_container, profileFragment, "3").hide(profileFragment).commit();
fragmentManager.beginTransaction().add(R.id.fragment_container, colorFragment, "2").hide(colorFragment).commit();
fragmentManager.beginTransaction().add(R.id.fragment_container,homeFragment, "1").commit();
Above solution loads all the fragments on the creation of activity which isn't a efficient scnario
- Using NavHost : It refresh the fragment every time.
This also not working for me.
Please Help:
What I want to acheive: 1.The fragment should only load when I click on the icon for the first time. 2.All the fragments should not load at the time of activity creation. 3.When I revist the fragment It should not load again, I should stay at previous state ex. scrolled till 25th card
//Its should be like playstore,youtube where when we click on icon it loads the data, when we revisit the state will be there.