Home > Back-end >  how to stop CountDownTimer in another Fragment?
how to stop CountDownTimer in another Fragment?

Time:07-04

I have three fragment, A -> B -> C. I started CountDownTimer in A fragment and want to stop it in C fragment. please help me!

CodePudding user response:

Your best bet would be to use a ViewModel tied to the Activity of the Fragments (so shared between fragments), and start the CountDown there. Then in Fragment C you just need to get the same ViewModel and stop the CountDown from there. |

For example, by using implementation "androidx.fragment:fragment-ktx:1.4.0" you can do in fragment A

private val viewModel: MyActivityViewModel by activityViewModels()

and in onCreateView() call your method that starts the timer viewModel.startCountDown()

Then in Fragment C

private val viewModel: MyActivityViewModel by activityViewModels()

and in onCreateView() call the method stopping it viewModel.stopCountDown()

  • Related