我希望您能够编写代码,以使得在不需要用户点击菜单键的情况下,程序能够自动打开选项菜单。请问应该如何实现?
或者只需调用 Activity.openOptionsMenu()?
显然,在onCreate方法中这样做会导致应用程序出错,因为Activity还未附加到窗口。正确的做法如下:
@Override
public void onAttachedToWindow() {
openOptionsMenu();
};
...它有效。
super.onAttachedToWindow()
作为函数的第一行会更好。 - Stephen Hosking对于使用Support Library
的新Toolbar
类的开发者,这是如何完成的:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.showOverflowMenu();
将这行代码放在你的onResume()函数中,这应该会有所帮助!
new Handler().postDelayed(new Runnable() {
public void run() {
openOptionsMenu();
}
}, 1000);
在名为MainActivity的活动内部的OnClickListener中:
MainActivity.this.openOptionsMenu();
getSupportActionBar().openOptionsMenu();
有两种方法可以做到:
Activity.getWindow().openPanel(Window.FEATURE_OPTIONS_PANEL, event);
event
参数是描述用于打开菜单的按键的KeyEvent
,它可以根据所使用的键盘类型修改菜单的显示方式。
或者...通过模拟用户按下按钮:
IWindowManager wManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
KeyEvent kd = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SOFT_LEFT);
KeyEvent ku = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SOFT_LEFT);
wManager.injectKeyEvent(kd.isDown(), kd.getKeyCode(), kd.getRepeatCount(), kd.getDownTime(), kd.getEventTime(), true);
如果你在你的视图内部,你可以写
((Activity)getContext()).openOptionsMenu();
KeyEvent
。这会使选项菜单出现。BaseInputConnection mInputConnection = new BaseInputConnection( findViewById(R.id.main_content), true);
KeyEvent kd = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU);
KeyEvent ku = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MENU);
mInputConnection.sendKeyEvent(kd);
mInputConnection.sendKeyEvent(ku);
toolbar.showOverflowMenu()
不起作用。 openOptionsMenu()
对我也不起作用。 相反,以下方法对我有用:new Handler().postDelayed(new Runnable() {
@Override
public void run() {
toolbar.showOverflowMenu();
}
}, 500);