Android 架构组件:同一视图模型的多个实例
Android Architecture Components: Multiple instances of the same view model
我是 Android 架构组件的新手,我已阅读 this 教程。我对它所说的部分感兴趣:
This allows you to have an app that opens a lot of different instances of the same Activity or Fragment, but with different ViewModel information. Let’s imagine if we extended our Court-Counter example to have the scores for multiple basketball games. The games are presented in a list, and then clicking on a game in the list opens a screen that looks like our current MainActivity, but which I’ll call GameScoreActivity.
假设我有一个 ViewModel MyViewModel
。我想创建这个视图模型的列表,但直到运行时我才知道这个列表中的元素数量。在 for 循环中创建视图模型实例方便吗?我可以创建多少个实例?实例数会影响性能吗?
Activity 实例和 ViewModel 实例之间存在一对一的关系。您可以有几个相同 Activity 的实例,并且每个实例都应该有自己独特的 ViewModel 实例。在单个 Activity 实例中拥有相同 ViewModel class 的多个实例是没有意义的。
ViewModel 提供程序采用可选的 key
,您可以使用它来区分 ViewModel 实例。
我是 Android 架构组件的新手,我已阅读 this 教程。我对它所说的部分感兴趣:
This allows you to have an app that opens a lot of different instances of the same Activity or Fragment, but with different ViewModel information. Let’s imagine if we extended our Court-Counter example to have the scores for multiple basketball games. The games are presented in a list, and then clicking on a game in the list opens a screen that looks like our current MainActivity, but which I’ll call GameScoreActivity.
假设我有一个 ViewModel MyViewModel
。我想创建这个视图模型的列表,但直到运行时我才知道这个列表中的元素数量。在 for 循环中创建视图模型实例方便吗?我可以创建多少个实例?实例数会影响性能吗?
Activity 实例和 ViewModel 实例之间存在一对一的关系。您可以有几个相同 Activity 的实例,并且每个实例都应该有自己独特的 ViewModel 实例。在单个 Activity 实例中拥有相同 ViewModel class 的多个实例是没有意义的。
ViewModel 提供程序采用可选的 key
,您可以使用它来区分 ViewModel 实例。