Android 按钮打开错误的活动

Han*_*ney 0 android button android-intent android-activity

我的主页上有三个按钮。当我尝试点击它们时会发生一些奇怪的事情。例如,当我单击 NewGame 按钮时,它首先显示分数按钮应显示的内容,然后如果我单击后退按钮,它将继续显示它打算显示的活动。使用“关于”按钮,我必须单击返回两次(它显示 newGame 活动和分数活动。发生这种情况有什么原因吗?

public class Sakurame extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

    //set up click listeners for buttons
    View HighScoreButton = findViewById(R.id.highscore_button);
    HighScoreButton.setOnClickListener(this);
    View newButton = findViewById(R.id.new_button);
    newButton.setOnClickListener(this);
    View aboutButton = findViewById(R.id.about_button);
    aboutButton.setOnClickListener(this);

}

@Override
public boolean onCreateOptionsMenu(Menu menu){
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()){
    case R.id.settings:
        startActivity(new Intent(this, Prefs.class));
        return true;
        // More items go here (if any)
    }
    return false;
}

public void onClick(View v){
    switch(v.getId()){
    case R.id.about_button:
        Intent i = new Intent(this, About.class);
        startActivity(i);
    case R.id.new_button:
        Intent i2 = new Intent(this, HighScore.class);
        startActivity(i2);
    case R.id.highscore_button:
        Intent i3 = new Intent(this, DisplayScores.class);
        startActivity(i3);
        //break;

        // more buttons go here (if any)
    }
}
Run Code Online (Sandbox Code Playgroud)

key*_*rdP 5

尝试在 onClick 方法中的break;each 之后添加startActivity

编辑以澄清。这确保一旦遇到 case,switch语句就会被中断,而不是移动到下一个 case 语句。

    case R.id.about_button:
        Intent i = new Intent(this, About.class);
        startActivity(i);
        break;
    case R.id.new_button:
        Intent i2 = new Intent(this, HighScore.class);
        startActivity(i2);
        break;
    case R.id.highscore_button:
        Intent i3 = new Intent(this, DisplayScores.class);
        startActivity(i3);
        break;
Run Code Online (Sandbox Code Playgroud)

  • 只是为了补充说明:Case 语句级联。因此,如果您不在每个 case 语句后添加 break,则每个后续的 case 语句都将运行... (4认同)