James
James

Reputation: 67

Android: Communicating with common functions regardless of Class

I have a game with different levels, with lots of shared code between the levels. So I have MainActivity that contains all the shared code, and this loads a fragment LevelOne for each level with the level specific code in it. I need to use fragments as I also load other fragments with other UI components in them.

The level fragments all contain functions of the same name with code unique to each level, e.g. StartGame() and PauseGame(), which MainActivity calls when necessary. How do I load a single object that allows me to access these functions, regardless of what fragment it is?

E.g. in python I would do:

// 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()      

but in Java I cannot do this as I have to specify the object's class beforehand, which I do not know and instead I have to have these if conditions everywhere I refer to the level:

// 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();
}

Upvotes: 0

Views: 26

Answers (1)

Martin Zeitler
Martin Zeitler

Reputation: 76699

Why you need another class for each level?

Level levelOne = new Level(1);  
Level levelTwo = new Level(2);

Upvotes: 1

Related Questions