在设置应用程序中更改字体后,将重新创建ViewModel

时间:2019-03-30 07:00:08

标签: viewmodel

ViewModel正在按我的预期进行屏幕旋转。但是,当在“设置应用程序”中更改字体时,ViewModel消失并重新创建。没有幸存。我认为ViewModel使得saveInstanceState是无用的。配置更改不包括字体更改吗?

https://developer.android.com/topic/libraries/architecture/viewmodel

  

ViewModel类旨在以生命周期感知的方式存储和管理与UI相关的数据。 ViewModel类允许数据在配置更改(例如屏幕旋转)中幸存下来。

我的简单代码。

class MyViewModel: ViewModel() {
  var abc: String? = null
}

class MyActvitiy: AppCompatActivity() {
  private lateinit var viewModel: MyViewModel

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_my)

    viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)

    // when screen rotation
    // viewModel.abc is "1"
    // when font change
    // viewModel.abc is null

    if (savedInstanceState == null) {
      viewModel.abc = "1"
      supportFragmentManager.beginTransaction()
          .replace(R.id.container, MyFragment.newInstance())
          .commitNow()
    }
  }
}

class MyFragment: Fragment() {
  private lateinit var viewModel: MyViewModel

  override fun onCreateView(
      inflater: LayoutInflater,
      container: ViewGroup?,
      savedInstaceState: Bundle?) {
    viewModel = activity?.run {
        ViewModelProviders.of(this).get(MyViewModel::class.java)
    } ?: throw Exception("Invalid Activity")

    binding = DataBindingUtil.inflate(layoutInflater, R.layout.fragment_my, container, false)
    return binding.root
  }
}

0 个答案:

没有答案