簡體   English   中英

調用 Fragment onStop 時停止計時器

[英]Stop a timer when Fragment onStop is called

當我試圖停止我的計時器時遇到了問題。 此計時器是在 FragmentViewModel 中創建的。 如果我離開應用程序,計時器會繼續運行。 我正在尋找阻止他的方法,但我無法從 Fragments onStop() 函數訪問他,因為他是在 ViewModel 中創建的,它僅在 Fragments onCreate() 函數中被引用。 任何人都知道如何解決這個問題?

這就是我創建 ViewModel 的方式(里面有計時器):

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val binding: GameFragmentBinding = DataBindingUtil.inflate(
        inflater, R.layout.game_fragment, container, false)


    val application = requireNotNull(this.activity).application

    val dataSource = TranslationDB.getInstance(application).translationDBDao

    val viewModelFactory = GameFragmentViewModelFactory(dataSource, application)

    val gameFragmentViewModel =
        ViewModelProviders.of(
            this, viewModelFactory).get(GameFragmentViewModel::class.java)


    binding.gameFragmentViewModel = gameFragmentViewModel

提前致謝!

您可以使用 ViewModels onCleared()回調。

要了解何時調用它(以便您可以決定它是否合適),請參閱此問題和答案When is the viewmodel onCleared called

如果您想根據生命周期事件在您的視圖模型中執行某些操作,請讓您的視圖模型實現LifecycleObserver接口,然后在您的視圖模型中執行

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop() {
    // stop timer
}

在你的片段中,在onCreateView你做

lifecycle.addObserver(viewmodel)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM