2010-10-19 101 views
0

從基本方法開始 - 選項菜單。選項菜單取消事件[Android]

問題:什麼是捕獲取消(返回)事件的最佳方式?即用戶改變主意並擊中後退箭頭。問題是我想取消暫停我的一個應用程序線程。

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 

    onPause(); 

    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.game_menu, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle item selection 
    switch (item.getItemId()) { 

    case R.id.preferences: 
    Intent settingsActivity = new Intent(this, PreferencesActivity.class); 
    startActivity(settingsActivity); 
    return true; 

    case R.id.quit: 
    finish(); 
    return true; 

    default: 
    return super.onOptionsItemSelected(item); 
    } 
} 

有沒有像@Override onCancelOptionsMenu ?? ??

回答

2

just whith onOptionsMenuClosed()我們無法區分用戶是否用後退/菜單按鈕取消菜單,或者是否選擇了某個項目。

我們可以通過使用模擬即onCancel()事件:

onOptionsMenuClosed() onOptionsItemSelected() 和布爾保持狀態:

private boolean bMenuCancelled = true; 

@Override 
public boolean onOptionsItemSelected(MenuItem item) 
{ 
    if(item.getItemId()<= YOUR_MAX_MENU_ITEM && item.getItemId()>= YOUR_MIN_MENU_ITEM) 
     bMenuCancelled = false; 
    else 
     bMenuCancelled = true; 

    //... 
} 

@Override 
public void onOptionsMenuClosed(Menu menu) 
{ 
    super.onOptionsMenuClosed(menu); 

    if(bMenuCancelled) 
     //here the menu has been closed by clicking outside the menu 
    else 
     //here the menu has been closed by selecting an item 

}