I have three buttons on my main page. Something weird happens when I try to click on them. For example, when I click on the NewGame button, it first displays what the scores button should display, and then if I click the back button it will proceed to display the activity that it was meant to. With the About button, I have to click back twice (it displays the newGame activity and the scores activity. Is there a reason why this is happening?
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:
startActivit开发者_JAVA百科y(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)
}
}
Try adding break;
after each startActivity
within the onClick method.
Edit to clarify. This ensures that once the case has been met, the switch
statement is broken from instead of moving on to the next case statement.
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;
精彩评论