当我从菜单栏中单击选项菜单项“设置”时,我想导航至另一个Activity
。实际没有任何反应。我已经检查了此处发布的类似问题,但我可以理解为什么这不适用于选项菜单。
参见下面的代码:
Can't go to a new activity from selected option from option menu
<item
android:id="@+id/mySettings"
android:title="@string/action_settings" />
<item
android:id="@+id/logout"
android:title="log out" />
代码:
public class Dashboard extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.app_bar_menu,menu);
return super.onCreateOptionsMenu(menu);
}
public void openConfigure(){
Intent intent = new Intent(this,Configure.class);
this.startActivity(intent);
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.mySettings:
openConfigure();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
答案 0 :(得分:1)
使用onOptionsItemSelected
代替onContextItemSelected
,因为您使用的是OptionMenu
而不是ContextMenu
。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.mySettings:
openConfigure();
break;
}
return super.onOptionsItemSelected(item);
}
答案 1 :(得分:0)
要选择一个选项菜单项,您必须重写onOptionItemSelected(): 尝试下面的代码
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.mySettings:
openConfigure();
break;
}
return true;
}