2011-02-16 84 views
11

我的XML菜單定義將項目R.id.menu_refresh的啓用狀態設置爲false。當應用程序運行時,菜單項呈灰色並禁用。爲什麼此應用程序中的代碼不啓用該項目?如何充氣Android選項菜單並將項目設置爲Enabled = false?

public boolean onCreateOptionsMenu(Menu menu) 
{ 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.main, menu); 
    MenuItem refresh = menu.getItem(R.id.menu_refresh); 
    refresh.setEnabled(true); 
    return true; 
} 

我錯過了什麼?

回答

18

嘗試menu.findItem()而不是getItem()getItem()需要一個來自[0,size]的索引,而findItem()需要一個id。

+0

天才,就是這樣。非常感謝。 – 2011-02-16 20:29:49

8

這是我在我的菜單處理活動做...

//Android Activity Lifecycle Method 
// This is only called once, the first time the options menu is displayed. 
@Override 
public boolean onCreateOptionsMenu(Menu menu) 
{ 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.mainmenu, menu); 
    return true; 
} 


//Android Activity Lifecycle Method 
// Called when a panel's menu is opened by the user. 
@Override 
public boolean onMenuOpened(int featureId, Menu menu) 
{ 
    MenuItem mnuLogOut = menu.findItem(R.id.main_menu_log_out_id); 
    MenuItem mnuLogIn = menu.findItem(R.id.main_menu_log_in_id); 
    MenuItem mnuOptions = menu.findItem(R.id.main_menu_options_id); 
    MenuItem mnuProfile = menu.findItem(R.id.main_menu_profile_id); 


    //set the menu options depending on login status 
    if (mBoolLoggedIn == true) 
    { 
     //show the log out option 
     mnuLogOut.setVisible(true); 
     mnuLogIn.setVisible(false); 

     //show the options selection 
     mnuOptions.setVisible(true); 

     //show the edit profile selection 
     mnuProfile.setVisible(true); 
    } 
    else 
    { 
     //show the log in option 
     mnuLogOut.setVisible(false); 
     mnuLogIn.setVisible(true); 

     //hide the options selection 
     mnuOptions.setVisible(false); 

     //hide the edit profile selection 
     mnuProfile.setVisible(false); 
    } 

    return true; 
} 


//Android Activity Lifecycle Method 
// called whenever an item in your options menu is selected 
@Override 
public boolean onOptionsItemSelected(MenuItem item) 
{ 
    // Handle item selection 
    switch (item.getItemId()) 
    { 

    case R.id.main_menu_log_in_id: 
    { 
     ShowLoginUI(); 
     return true; 
    } 

    case R.id.main_menu_log_out_id: 
    { 
     ShowGoodbyeUI(); 
     return true; 
    } 

    case R.id.main_menu_options_id: 
    { 
     ShowOptionsUI(); 
     return true; 
    } 

    case R.id.main_menu_profile_id: 
    { 
     ShowProfileUI(); 
     return true; 
    } 

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

我喜歡這種方法,因爲它使代碼不錯,模塊化

相關問題