简体   繁体   中英

How can I keep the timer running when I navigate to different fragment with bottom navigation in my android app?

The fragment gets destroyed and the timer resets to 00:00 when I navigate using bottom navigation. I have used Chronometer. I tried retainInstance=true but it only helps when screen is rotated.

MainActivity.kt

class MainActivity : AppCompatActivity() {
    private lateinit var navController: NavController



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navHostFragment =supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        navController =navHostFragment.findNavController()

        bottom_nav.setupWithNavController(navController)

    }

} 

TimerFragment.kt

class TimerFragment : Fragment(R.layout.fragment_timer) {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        super.onViewCreated(view, savedInstanceState)
       
          //code
        
    }

     //Few functions
}

I would suggest you to use ViewModel approach, ie ActivityViewModel and FragmentViewModel

Hold the timer value in your FragmentViewModel and when fragment is about to be destroyed update the timer value in ActivityViewModel in the Activity.

Similarly, in onCreate() of fragment update the timer value in FragmentViewModel from ActivityViewModel

The reason is that ViewModel 's preserve data after activity recreation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM