在 Fragment 之间发送变量并在 ViewModel 中使用它

Sending variables between Fragments and using it in the ViewModel

我正在发送一个变量并在片段中接收它,但这对于 ViewModel 中的用户界面是必需的。在 ViewModel 中访问变量的最佳方式是什么?

发送片段

val gameMode = 1
val action = PlayFragmentDirections.actionPlayFragmentToGameFragment(gameMode)
findNavController().navigate(action)

正在接收片段

    binding = DataBindingUtil.inflate(inflater, R.layout.game_fragment,
        container,false)

    viewModel = ViewModelProviders.of(this).get(GameViewModel::class.java)

    val gameFragmentArgs by navArgs<GameFragmentArgs>()
    var x = gameFragmentArgs.gamemode

    binding.gameViewModel = ViewModel
    binding.lifecycleOwner = this

使用 ViewModelFactory

游戏片段:

    val gameFragmentArgs by navArgs<GameFragmentArgs>()
    val x = gameFragmentArgs.gamemode

    viewModelFactory = GameViewModelFactory(x)
    viewModel = ViewModelProviders.of(this, viewModelFactory).get(GameViewModel::class.java)

游戏视图模型工厂:

class GameViewModelFactory(private val gameMode: Int) : ViewModelProvider.Factory{
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
    if (modelClass.isAssignableFrom(GameViewModel::class.java)){
        return GameViewModel(gameMode) as T
    }
    throw IllegalArgumentException("Unknown ViewModel class")
}

}