android-如何以编程方式打开选项菜单?
我想以编程方式打开optionsMenu,而无需用户单击菜单键。 我该怎么做?
11个解决方案
92 votes
或者只是调用Activity.openOptionsMenu()?
Robby Pond answered 2019-11-11T04:20:58Z
32 votes
显然,在onCreate中执行此操作会中断应用程序,因为Activity尚未附加到窗口。 如果您这样做:
@Override
public void onAttachedToWindow() {
openOptionsMenu();
};
...有用。
Kovač answered 2019-11-11T04:21:28Z
16 votes
对于使用Support Library新的Toolbar类的开发人员,这是这样做的:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.showOverflowMenu();
marmor answered 2019-11-11T04:21:52Z
11 votes
将这行代码放在您的onResume()中,这应该有所帮助!
new Handler().postDelayed(new Runnable() {
public void run() {
openOptionsMenu();
}
}, 1000);
Royston Pinto answered 2019-11-11T04:22:16Z
8 votes
从名为MainActivity的活动中的OnClickListener中:
MainActivity.this.openOptionsMenu();
Oded Breiner answered 2019-11-11T04:22:39Z
5 votes
如果使用AppCompatActivity
getSupportActionBar().openOptionsMenu();
Abhijit answered 2019-11-11T04:23:03Z
1 votes
有两种方法:
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);
Cristian answered 2019-11-11T04:23:40Z
0 votes
如果您在视图中,则可以编写
((Activity)getContext()).openOptionsMenu();
Fabio Bianconi answered 2019-11-11T04:24:06Z
0 votes
经过长时间的研究和多次尝试,唯一的方法似乎是模拟KeyEvent。这将使options菜单出现:
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);
Lotfi answered 2019-11-11T04:24:31Z
0 votes
对我来说,在onClick中声明toolbar.showOverflowMenu()是行不通的。 openOptionsMenu()也不适用于我。 除了以下方式对我有用之外,
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
toolbar.showOverflowMenu();
}
}, 500);
Nanda Gopal answered 2019-11-11T04:24:56Z
0 votes
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(0xFFFFFFFF);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
toolbar.showOverflowMenu();
}
}, 100);
Mukesh KrishMeg answered 2019-11-11T04:25:14Z