【问题标题】:Stop a timer when Fragment onStop is called调用 Fragment onStop 时停止计时器
【发布时间】:2019-11-26 16:54:29
【问题描述】:

我在尝试停止计时器时遇到问题。这个计时器是在 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

提前致谢!

【问题讨论】:

    标签: android android-fragments kotlin countdowntimer android-viewmodel


    【解决方案1】:

    如果您想根据生命周期事件在视图模型中执行某些操作,请让您的视图模型实现LifecycleObserver 接口,然后在您的视图模型中执行

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

    在你的片段中,在onCreateView 你做

    lifecycle.addObserver(viewmodel)
    

    【讨论】:

    • 这绝对是我想要的。第一次听说这种处理方式。你能告诉我如何在我的视图模型中实现 LifecycleObserver 接口吗?已经非常感谢了!
    【解决方案2】:

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

    要了解何时调用它(以便您决定是否合适),请查看此问题和答案When is the viewmodel onCleared called

    【讨论】:

    • 我以前看过那个帖子,然后又试了一次,我认为这里没有调用它。当用户刚刚离开应用程序时,如果我理解正确,就不应该调用它,对吧?我需要的是完全适合这种情况的东西,因为计时器应该被停止并且能够恢复。
    猜你喜欢
    • 1970-01-01
    • 2012-03-23
    • 2017-12-26
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多