【发布时间】: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