سؤال

I simply want to the options menu to toggle my sliding menu but havent found the standard click listener for the options button. Is OnPrepareOptionsMenu the only method that fires when clicking the options button? I don't really want to use this method because this method also gets fired when the application starts up.

هل كانت مفيدة؟

المحلول

UPDATE: for the menu button (hardware button), you can use the event onKeyUp:

public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        if (event.getAction() == KeyEvent.ACTION_UP)
        {
            Log.d("onkeyup", "onkeyup");
            return true;
        }
    }
    return super.onKeyUp(keyCode, event);
}

NOTE: the solution below is for the ActionBar

Just override the onOptionsItemSelected function. You can then listen the click event on all the menu items and trigger the actions you want according to the case:

Here is an example from a main activity class:

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch(item.getItemId()) {

    case R.id.menu_calendar:
        makeToast("Loading...");
        openCalendar();
        break;
    case R.id.menu_search:
        makeToast("Loading...");
        openSearch();
        break;      
    case R.id.menu_settings:
        openSettings();
        break;
    case R.id.menu_help:
        openHelp();
        break;
    case R.id.menu_about:
        mBackupManager.dataChanged();
        openAbout();
        break;
    }
    return true;
}

نصائح أخرى

You need to Override menu button, so that when user clicks Menu your code would be executes instead of opening menu.Like this

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ( keyCode == KeyEvent.KEYCODE_MENU ) {
        //Put the code for an action menu from the top here
        return true;
    }
return super.onKeyDown(keyCode, event);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top