2014-04-02 98 views
0

我在onCreate中使用下面的代碼在操作欄中顯示下拉菜單。該代碼工作正常,它顯示下拉菜單並執行我在onNavigationItemSelected中添加的任務。但他只發生一次,即如果我第一次選擇菜單項2 Toast顯示「Selected」消息並執行asynctask。當我重新選擇菜單項2沒有任何反應!爲什麼會出現這個問題,我該如何擺脫它呢?在下拉菜單中重新選擇菜單項時沒有任何反應

getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); 
     final LinearLayout mainLayout = (LinearLayout) this 
       .findViewById(R.id.linearLayout1); 

     ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() { 

      @Override 
      public boolean onNavigationItemSelected(int itemPosition, 
        long itemId) { 

       if (actions[itemPosition].toString().equals("exit")) { 

        System.exit(0); 
       } 
       if (actions[itemPosition].toString().equals(
         "Menu Item 2")) { 

        Toast.makeText(getApplicationContext(),"Selected" ,Toast.LENGTH_LONG).show(); 
        code="2"; 
        //call to an asynctask 

       } 
       return false; 
      } 
     }; 

    getActionBar().setListNavigationCallbacks(adapter, navigationListener); 

回答

0

你需要閱讀這些鏈接那麼你的問題就會解決掉你的戰略調用菜單項不正確所以按照這些鏈接

http://developer.android.com/reference/android/view/MenuItem.html
http://developer.android.com/guide/topics/ui/menus.html
http://www.androidhive.info/2011/09/how-to-create-android-menus/
Handling a Menu Item Click Event - Android
Creating an Options Menu in Android

這些代碼是mor Ë有益的,使下拉項選擇項目

代碼是上面: - 轉到項目和res文件夾,然後菜單/然後菜單項

<menu xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:id="@+id/new_game" 
     android:icon="@drawable/menu_addnew" 
     android:title="new_game" 
     android:showAsAction="ifRoom"/> 
<item android:id="@+id/help" 
     android:icon="@drawable/menu_addnew" 
     android:title="help" /> 
</menu> 


    and then in java file you have use this code 

    public class AndroidMenusActivity extends Activity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
} 

// Initiating Menu XML file (menu.xml) 
    @Override 
public boolean onCreateOptionsMenu(Menu menu) 
{ 
    MenuInflater menuInflater = getMenuInflater(); 
    menuInflater.inflate(R.layout.menu, menu); 
    return true; 
} 
@Override 
public boolean onOptionsItemSelected(MenuItem item) 
{ 

    switch (item.getItemId()) 
    { 
    case R.id.new_game: 
     // Single menu item is selected do something 
     // Ex: launching new activity/screen or show alert message 
     Toast.makeText(AndroidMenusActivity.this, "Bookmark is Selected", Toast.LENGTH_SHORT).show(); 
     return true; 

    case R.id.help: 
     Toast.makeText(AndroidMenusActivity.this, "Save is Selected", Toast.LENGTH_SHORT).show(); 
     return true; 
    default: 
     return super.onOptionsItemSelected(item); 
    } 
+0

這是鏈接只能回答和鏈接只回答您的.xml文件是不鼓勵的 – Raghunandan

+0

這意味着你想要: - 我們爲你編碼,這將爲你的問題做出有用的代碼,如果你仔細閱讀這些鏈接,那麼你可以輕鬆實現 – Amitsharma

+0

我爲你添加了一些其他代碼,請稍候 – Amitsharma