我在单击选项菜单中的项目时遇到问题。 我在网站https://developer.android.com/guide/topics/ui/menus上读过如何创建菜单,我似乎做得很对,但仍然不起作用。 菜单是存在的,它是可见的,但是当我执行单击时什么也没有发生。 此外,Logcat中没有错误。
我重写了方法OnCreateOptionsMenu
和OnOptionSitemSelected
,如下所示:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_script, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
Toast.makeText(this, item.getItemId(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()){
case R.id.edit_menu_script_item:
Toast.makeText(this, "Opening edit page...", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),EditScript.class);
intent.putExtra("script",script);
startActivity(intent);
return true;
case R.id.characters_menu_script_item:
Toast.makeText(this, "Opening characters list...", Toast.LENGTH_SHORT).show();
return true;
case R.id.delete_menu_script_item:
Toast.makeText(this, "Deleting script...", Toast.LENGTH_SHORT).show();
return true;
case R.id.scenes_menu_script_item:
Toast.makeText(this, "Opening scenes list...", Toast.LENGTH_SHORT).show();
return true;
case R.id.share_menu_script_item:
Toast.makeText(this, "Opening sharing dialog...", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
点击菜单的第一项时,我想打开另一个名为editscript
的activity。
菜单的XML文件为:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:title="@string/edit"
android:id="@+id/edit_menu_script_item"
app:showAsAction="always"
android:icon="@drawable/ic_edit"/>
<item android:title="@string/delete"
android:id="@+id/delete_menu_script_item"
app:showAsAction="never"/>
<item android:title="@string/share"
android:id="@+id/share_menu_script_item"
app:showAsAction="never"/>
<item android:title="@string/scenes"
android:id="@+id/scenes_menu_script_item"
app:showAsAction="never"/>
<item android:title="@string/characters"
android:id="@+id/characters_menu_script_item"
app:showAsAction="never"/>
</menu>
我还应该写些什么来让这一切顺利吗?
提前谢谢!
试试这个代码。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.delete_menu_script_item:
Toast.makeText(this, "Deleting script...", Toast.LENGTH_SHORT).show();
break;
case R.id.characters_menu_script_item:
Toast.makeText(this, "Opening characters list...", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}