2012-10-23 34 views
0

我開發一個Android應用程序,和我在動作條兩個菜單,我爲他們每個人的行動,但我只能夠訪問其中的一個,這是我的代碼做動作欄上不同的動作

@Override 
public boolean onOptionsItemSelected(MenuItem item) 
{ 
    Toast.makeText(this, "Studentsite News", Toast.LENGTH_LONG).show(); 
    Intent i = new Intent(this, ssnews.class); 
    startActivity(i); 
    return true; 
} 
public boolean onOptionsItemSelected1(MenuItem item) 
{ 
    Toast.makeText(this, "About", Toast.LENGTH_LONG).show(); 
    Intent i = new Intent(this, about.class); 
    startActivity(i); 
    return true; 
} 

你有任何想法解決它嗎?我真的很感激。

+1

爲什麼兩個'onOptionsItemSelected'?只需使用'switch case'來查看選擇了哪個菜單並開始相應的活動。 –

+0

是第一個menuitem工作,第二個不工作? –

+0

在onOptionsItemSelected.Updating代碼中使用開關。 –

回答

2

閱讀本頁面:http://developer.android.com/guide/topics/ui/menus.html#RespondingOptionsMenu

本節演示了使用onOptionsItemSelected方法(實際上與Menus有關的任何操作)的理想方法。

從頁面的摘錄(與您的情況):

@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); 
    } 
} 
0
@Override 
    public boolean onOptionsItemSelected(MenuItem item) 
    { 

     switch (item.getItemId()) { 

     case 1: 
    Toast.makeText(this, "Studentsite News", Toast.LENGTH_LONG).show(); 
    Intent i = new Intent(this, ssnews.class); 
    startActivity(i); 
    return true;    
     case 2: 
     Toast.makeText(this, "About", Toast.LENGTH_LONG).show(); 
    Intent i = new Intent(this, about.class); 
    startActivity(i); 

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


    } 

    }