在我的应用程序中,有很多被称为关卡的 Activity 。一项 Activity 是奖励 Activity 。当我赢得一级时,奖励 Activity 开始。现在我想重播 1 级。为此,我使用了 getExtra()。当我点击重播按钮时,我的应用程序崩溃了。
Houselevel1.java
public void getReward(){
if(count == 3) {
Intent intent = new Intent("com.creatives.arfa.revealthesecretsgame.Reward");
intent.putExtra("activity", "level1");
startActivity(intent);
}
}
HouseLevel2.java
public void getReward(){
if(count == 3) {
Intent intent = new Intent("com.creatives.arfa.revealthesecretsgame.Reward");
intent.putExtra("activity", "level2");
startActivity(intent);
}
}
奖励.java
public void replayLevel() {
replay = (ImageButton) findViewById(R.id.replay);
Intent intent= getIntent();
activity = intent.getStringExtra("activity");
replay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View paramView) {
if(activity.equals("level2")){
Intent intent = new Intent("com.creatives.arfa.revealthesecretsgame.HouseLevel2");
startActivity(intent);
}
if(activity.equals("level1")){
Intent intent = new Intent("com.creatives.arfa.revealthesecretsgame.Houselevel1");
startActivity(intent);
}
}
});
}
最佳答案
使用您发布的 java 代码,在 Reward.java
文件中,您试图创建另一个 Intent 对象,其名称与其上方范围内声明的对象同名。因此,构建永远不会成功。
此外,当您声明 Intent 时,您必须传递 activity_name.class
文件。
你可以尝试的东西:
1) HouseLevel1.java
public void getReward(){
if(count == 3) {
Intent intent = new Intent(getApplicationContext(), com.creatives.arfa.revealthesecretsgame.Reward.class);
intent.putExtra("activity", "level1");
startActivity(intent);
}
}
2) HouseLevel2.java
public void getReward(){
if(count == 3) {
Intent intent = new Intent(getApplicationContext(), com.creatives.arfa.revealthesecretsgame.Reward.class);
intent.putExtra("activity", "level2");
startActivity(intent);
}
}
3) 奖励.java
public void replayLevel() {
replay = (ImageButton) findViewById(R.id.replay);
Intent intent= getIntent();
activity = intent.getStringExtra("activity");
replay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View paramView) {
if(activity.equals("level2")){
Intent intent = new Intent(getApplicationContext(), com.creatives.arfa.revealthesecretsgame.HouseLevel2.class);
startActivity(intent);
}
else if(activity.equals("level1")){
Intent intent = new Intent(getApplicationContext(), com.creatives.arfa.revealthesecretsgame.Houselevel1.class);
startActivity(intent);
}
}
});
}
此外,如果您只是简单地使用 Reward.java
文件来获取之前的 Intent 数据,执行一些计算,并将一些数据发送回调用或父 Activity ,那么您可以只需使用 startActivityForResult()
方法,它会处理您尝试手动执行的操作。
这里有一篇小文章,也许能帮助你解决这个问题
关于java - 从 Activity 1 切换到 Activity 2 时应用崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51340175/