2011-06-29 225 views
1

我正嘗試創建一個android上下文菜單(當您按'菜單'按鈕時彈出的菜單)。我已經閱讀了所有我能找到的教程,沒有任何幫助。我是android開發新手。在Android中創建上下文菜單

我創建了menu.xml文件,但我不明白如何給ID的功能。這是我的代碼看起來如何:

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.menu, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle item selection 
    switch (item.getItemId()) { 
    case R.id.new_game: 
     newGame(); 
     return true; 
    case R.id.help: 
     showHelp(); 
     return true; 
    default: 
     return super.onOptionsItemSelected(item); 
    } 
} 

我沒有得到的東西:如何處理'newGame();'和'showHelp();'。我希望當我點擊一個菜單按鈕時,一個新的活動開始。我該怎麼做?

回答

1

的第一件事是你必須代碼是爲選項菜單不是上下文菜單 您可以撥打新的活動像下面

  1. 您可以直接調用不使用選項菜單的新活動

    Intent myIntent = new Intent(this, NewGame.class); 
    startActivity(myIntent); 
    
  2. ,如果你想給選項,用戶在按下菜單按鈕,然後嘗試下面的代碼

    @Override 
        public boolean onCreateOptionsMenu(Menu menu) { 
    
         menu.add(0, 0, 0, "New Game"); 
         menu.add(0, 1, 1, "Help"); 
         return super.onCreateOptionsMenu(menu); 
        } 
    
    @Override 
        public boolean onOptionsItemSelected(MenuItem item) { 
    
         if(item.getTitle().toString.equalsIgnoreCase("New Game")) { 
    
          Intent intent = new Intent(this, NewGame.class); 
          startActivity(intent); 
          finish(); 
          } 
          else if(item.getTitle().toString.equalsIgnoreCase("Help")) { 
           Toast.makeText(getBaseContext(), "Help", 2000).show(); 
           } 
         } 
    
+0

你們真棒!謝謝。 ;) – Simonas

0

這將啓動活動NewGame

Intent myIntent = new Intent(this, NewGame.class); 
startActivity(myIntent); 
+0

非常感謝你,這有助於。我是一個完整的noob。 :)) – Simonas