2011-05-11 166 views
0

我的主頁上有三個按鈕。當我嘗試點擊它們時會發生奇怪的事情。例如,當我點擊NewGame按鈕時,它會首先顯示分數按鈕應該顯示的內容,然後如果我單擊後退按鈕,它將繼續顯示其意圖的活動。隨着關於按鈕,我必須單擊後退兩次(它顯示newGame活動和成績的活動。有一個原因,這是怎麼回事?Android按鈕打開錯誤的活動

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) 
    } 
} 

回答

3

嘗試的onClick方法中的每個startActivity後加入break;

編輯澄清這確保了一旦此案已經滿足,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; 
+3

我想補充說明:Case語句卡斯卡德。因此,如果您在每個案例陳述後不添加中斷,則後續的每個案例陳述都會運行... – 2011-05-11 23:56:40

+0

是的,對不起,我應該更清楚一點。 – keyboardP 2011-05-11 23:57:37

+0

謝謝 - 它解決了一切。我沒有意識到他們級聯@。@ – 2011-05-12 00:28:02