以编程方式获取选项菜单的Android代码?

发布于 2024-11-02 08:07:43 字数 68 浏览 1 评论 0原文

显示活动后在 android 中以编程方式获取选项菜单的 Android 代码?

这可能吗? 提前致谢!!

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

Is this possible?
Thanks in advance!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

許願樹丅啲祈禱 2024-11-09 08:07:43

我可以通过挂钩 onAttachedToWindow() 事件来打开菜单。创建视图后,这将自动触发。我使用了以下代码:

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

当我尝试在“onCreate(...)”或“onPostCreate(...)”事件中打开选项菜单时,收到以下错误:“无法添加窗口 -- token null无效;您的活动正在运行吗?”似乎只有在绘制视图并将其注册到窗口后,选项菜单才可用。

顺便说一句,最好通过挂钩“onTouchEvent(Motion event)”来打开选项菜单,如下所示:

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

这样,如果用户点击或滑动活动,就会显示选项菜单。为了结束讨论,可以通过以下命令关闭选项菜单:

((Activity) mContext).closeOptionsMenu();

因此,可以使用以下命令“切换”选项菜单:

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

嗯,我希望这会有所帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文