2014-09-28 150 views
2

我正在做的教程和在添加操作按鈕部分,openSearch()和openSettings()未定義。所以我把它們作爲同一班級的私人空白。不過,在開關中,openSearch();顯然無法達到。當我刪除該案例時,下一個案例中的方法無法訪問。這是我的代碼。Android教程切換第一種情況下方法無法訪問

return super.onOptionsItemSelected(item); 
    // Handle presses on the action bar items 
    switch (item.getItemId()) { 
     case R.id.action_search: 
      openSearch(); 
      return true; 
     case R.id.action_settings: 
      openSettings(); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
    } 
private void openSettings() { 
    Toast.makeText(this, "Search button pressed", Toast.LENGTH_SHORT).show(); 
} 
private void openSearch() { 
    Toast.makeText(this, "Search button pressed", Toast.LENGTH_SHORT).show(); 
} 
+0

'返回值;'結束你的情況後,控制的方法流程,所以代碼(' )不會被調用(無法訪問) – Pshemo 2014-09-28 17:37:39

+0

這是Android Studio的優點之一,您稱之爲無法訪問的代碼。 – rekire 2014-09-28 17:38:17

+1

正如一邊:你應該擺脫在switch語句中使用資源ID作爲案例值的習慣。它不適用於資源ID值不是「最終」的庫項目。有關詳細信息,請參閱[此處](http://tools.android.com/tips/non-constant-fields)。 – 2014-09-28 17:40:37

回答

3

你應該在你的方法頂部擺脫return super.onOptionsItemSelected(item);,或交換機將永遠無法到達

相關問題