【发布时间】:2019-03-20 15:33:53
【问题描述】:
我有一个不同关卡的游戏,关卡之间有很多共享代码。所以我有包含所有共享代码的 MainActivity,这会为每个级别加载一个片段 LevelOne,其中包含特定于级别的代码。我需要使用片段,因为我还加载了其他带有其他 UI 组件的片段。
关卡片段都包含同名的函数,每个关卡都有唯一的代码,例如StartGame() 和 PauseGame(),MainActivity 在必要时调用它们。如何加载允许我访问这些功能的单个对象,而不管它是什么片段?
例如在 python 中我会这样做:
// Instantiation
int level_number = 1;
levels = [levelOne, levelTwo]
level = levels[level_number]
// Something happens and I want to start the currently selected level somewhere in MainActivity
level.StartGame()
但在 Java 中我不能这样做,因为我必须事先指定对象的类,我不知道,相反,如果我提到级别的任何地方的条件,我都必须有这些:
// Instantiation
LevelOne levelOne = new LevelOne();
LevelTwo levelTwo = new LevelTwo();
// Something happens and I want to start the currently selected level somewhere in MainActivity
if (level_number == 1) {
levelOne.StartGame();
} elif (level_number == 2) {
levelTwo .StartGame();
}
【问题讨论】:
标签: java android oop android-fragments