I have one User Activity class which has drawer menu (includes home page, my profil etc..). When user clicks the one of the menu item, I will load fragment such as HomePageFragment, MyProfilFragment etc..
Here is the code example:
public void navigationItemSelectedListener(DrawerLayout drawerLayout, NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(menuItem -> {
menuItem.setChecked(true);
int menuId = menuItem.getItemId();
switch (menuId){
case R.id.home_menu_item:
loadFragment(new HomePageFragment());
break;
// goes like that
Here is the loadFragment:
public void loadFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.user_page_activity_frame_layout, fragment);
fragmentTransaction.commit();
}
}
Now I have run CountDownTimer(60 seconds) in HomePageFragment, when counter is 0, I will run some methods().
However I can not do that. Because each time user navigates new item, then when back to the HomePage menu item, new HomePageFragment() is creating, therefore CountDownTimer starts with 60s again and again. What I want CounDownTimer to run even if user navigates another menu.
Note that, I had tried to create HomePageFragment attribute as global. But it didn't work. (Like 2 timer counts down. One says 60-59... another says 30-29 ...)
Problem here is, your Fragment
gets destroyed every time user navigates to another item.
To solve this
1.Either Create the Timer in your host activity instead the fragment, maybe inside navigationItemSelectedListener()
2.Make sure your fragment doesn't get destroyed everytime. Check How to resume Fragment from BackStack if exists