开发者

Android - Options Menu wont work

I am trying to create an Options menu in an Activity that gets started from a Service and then changes its UI based on messages from the Service passed via a Handler.

I set up the Options menu as follows:


     /** Menu creation and setup **/

        /* Creates the menu items */
        public boolean onCreateOptionsMenu(Menu menu) {
            menu.add(0, 1, 0, "Speaker");
            menu.add(0, 2, 0, "Mute");
            return true;
        }

        /* Handles item selections */
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case 1:
                //Do something here
                return true;
            case 2:
               //Do something here
                return true;
            }
            return false;
        } 开发者_Go百科 

But it never gets called when my application is run at all.

I have experienced problems where I need to use a Handler to change Text on the screen as the information is being passed on the wrong thread, could this same issue be the cause of the menu not displaying?

Is so how can I fix it as I cant override a method in a Handler


Make sure you aren't consuming the key event for the menu in a key handler. The menu button event is sent through key handlers before being handled by the onCreateOptionsMenu function. This could be happening in any view with focus, or by the activity itself. A quick way to fix this would be the following:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_MENU)
        return super.onKeyDown(keyCode, event);
    -- insert all other key handling code here --
    return false;
}


Try calling the super method in your overridden onCreateOptionsMenu method as follows:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    boolean result = super.onCreateOptionsMenu(menu);
    menu.add(0, 1, 0, "Speaker");
    menu.add(0, 2, 0, "Mute");

    return result;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜