1

Android code for getting Options Menu programmatically in android after displaying the Activity??

Is this possible? Thanks in advance!!

info
  • 2,152
  • 5
  • 22
  • 38

1 Answers1

0

I was able to open the menu by hooking the onAttachedToWindow() event. This would fire automatically after the view was created. I used the following code:

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    try {
        ((Activity) this).openOptionsMenu();        
    } catch (Exception ex) {
        Log.e("ERR", "Error: " + ex.getMessage());
    }
}

When I attempted to open the Option Menu in the "onCreate(...)" or "onPostCreate(...)" events, I received the following error: "Unable to add window -- token null is not valid; is your activity running?" It seems that the Option Menu is not available until the view is being drawn and registered to the Window.

As an aside, it may be preferable to open the Options Menu by hooking the "onTouchEvent(Motion event)" as in:

@Override
public boolean onTouchEvent(MotionEvent event) {
    ((Activity) this).openOptionsMenu();
    return super.onTouchEvent(event);
}

This way, the Options Menu is displayed if the user taps or swipes the activity. To round out the discussion, the Option Menu may be dismissed via the following command:

((Activity) mContext).closeOptionsMenu();

Thus, the Options Menu can be "toggled" by using the following commands:

    ((Activity) this).openOptionsMenu();
    ((Activity) this).closeOptionsMenu(); 

Well, I hope this helps.