Android - openOptionsMenu doesn't work in onCreate
Asked Answered
T

2

10

Is there any other way to call openOptionsMenu after activity is displayed without using something like this:

new Handler().postDelayed(new Runnable() {
            public void run() {
                openOptionsMenu();
            }
        }, 1000); 

Reference: http://groups.google.com/group/android-beginners/browse_frm/thread/b10a8ea840c07725/1ce48bb147a3ed1a?#1ce48bb147a3ed1a

EDIT: I would appreciate example like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Now I guess something like Window.Callback.onAttachedToWindow(...) should be done?
}
Townsley answered 5/5, 2010 at 22:1 Comment(1)
That solution is really quite fragileBlakely
B
21

I looked at Activity again, and it has had the method onAttachedToWindow, inherited from Window.Callback, since API level 5. If you are using this level, then you simply have to override this method in your Activity.

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    openOptionsMenu();
}

If you are using a version prior to 5, then you have to override the onAttachedToWindow method in View instead. This is very easy if your View is created in code. If it is created in XMl, then it isn't that much harder - you should find the instructions here helpful.

Blakely answered 6/5, 2010 at 3:0 Comment(4)
And where should I insert this override, as Activity doesn't have onAttachedToWindow?Townsley
Can you please give me complete example? Thanks in advance!Townsley
@kape123: I did some more research. I hope this clears things up.Blakely
Yeah... definitely it's clear now (I'm using API 4)... thanks a lot for your help! (I'll accept your answer and give it bounty ASAP)Townsley
K
-1

My solution

//Open menu manually from code 
    Timer timing = new Timer();
    timing.schedule(new TimerTask() {

                /**
                 * {@inheritDoc}
                 */
                @Override
                public void run() {

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            openOptionsMenu();
                        }
                    });

                }
            }, 1000);
Kone answered 10/2, 2011 at 6:27 Comment(3)
... that's worse version of code I already posted in my questionTownsley
hey, did you try it? I am using it in my own application on the market.Kone
It is generally a bad practice to use timer-based scheduling during the startup/loading, especially if you can use a dedicated callback.Hardesty

© 2022 - 2024 — McMap. All rights reserved.