Android按钮打开了错误的活动

时间:2011-05-11 23:46:34

标签: android button android-activity android-intent

我的主页上有三个按钮。当我试图点击它们时会发生奇怪的事情。例如,当我点击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)
    }
}

1 个答案:

答案 0 :(得分:3)

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

编辑以澄清。这确保了一旦满足案例,switch语句就会被打破,而不是转到下一个案例陈述。

    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;