9

I'm new to Android Architecture Components and I have read this tutorial. I'm interested in the part where it said:

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.

Let's say I have a ViewModel MyViewModel. And I want to create a list of this view model but I don't know the number of elements in this list until runtime. Is it convenient to create the view model instances inside a for loop? How many instances am I allowed to create? Will the number of instances affect performance?

4

2 回答 2

2

Activity 实例和 ViewModel 实例之间存在 1 对 1 的关系。您可以拥有同一个 Activity 的几个实例,并且每个实例都应该拥有自己唯一的 ViewModel 实例。在单个 Activity 实例中拥有相同 ViewModel 类的许多实例是没有意义的。

于 2018-02-20T06:50:29.213 回答
0

ViewModel 提供者采用一个可选项key,您可以使用它来区分 ViewModel 实例。

于 2021-12-08T22:16:32.573 回答