简体   繁体   中英

Start an Activity from a non-Activity class

I'm making a small game using Android studio wich have 3 activities : Menu , Main(Game) , WinScreen . When I try to go from Menu to Main or WinScreen to Main it works perfectly fine but when I try to launch an activity from the Main activity I get an error.

I have a method in a java file that checks if the player won and if that's the case it is supposed to launch the WinScreen activity.

boolean checkWin(GameBoard gameboard){
       if(compareTabs(gameboard) == true){
           System.out.println("Win !");
           Intent i = new Intent(MainActivity.this,WinActivity.class);
           startActivity(i);
           return true;
       }
       else{
           return false;
       }
}

And this is the error I get : error: not an enclosing class: MainActivity

This method is located in a file called GameBoard , GameBoard is used by the GameView Class who is launched at the start of the MainActivity

I know there is hundreds of posts similar to mine but I've pretty much tried everything I've found already and nothing seems to work and I'm pretty sure it's a really dumb issue .

I've already tried things like Intent i = new Intent(this,WinActivity.class);

Note that if this method is being called from outside of an Activity Context, then the Intent must include the Intent#FLAG_ACTIVITY_NEW_TASK launch flag. This is because, without being started from an existing Activity, there is no existing task in which to place the new activity and thus it needs to be placed in its own separate task.

Android developer documentation

Change the signature of checkWin() to include a Context as a parameter and then use that Context here:

boolean checkWin(GameBoard gameboard, Context context){
   if(compareTabs(gameboard) == true){
       System.out.println("Win !");
       Intent i = new Intent(context, WinActivity.class);
       context.startActivity(i);
       return true;
   }
   else{
       return false;
   }
}

If you are calling checkWin() from an Activity , you can just provide this as the Context parameter when calling it, because Activity is a Context :

(inside an Activity)
boolean win = whatever.checkWin(gameboard, this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM