Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

java - 从非活动类开始活动(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 . (我正在使用Android studio进行小型游戏,共有3个活动: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. (当我尝试从菜单转到主菜单,或从WinScreen转到主菜单时,它工作正常,但是当我尝试从Main活动启动活动时,出现错误。)

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. (我在java文件中有一个方法可以检查播放器是否获胜,是否应该启动WinScreen活动。)

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 (这是我得到的错误: 错误:不是封闭的类: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 (此方法位于一个名为GameBoard的文件中,该GameBoard由在MainActivity开头启动的GameView类使用。)

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); (我已经尝试过Intent i = new Intent(this,WinActivity.class);)

  ask by Deyami translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. (请注意,如果从活动上下文外部调用此方法,则该Intent必须包含Intent#FLAG_ACTIVITY_NEW_TASK启动标志。) 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 (Android开发人员文档)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...