我有一个带有设置菜单项的 xml,并且有一个打开 OptionsMenu 的按钮并且它正在工作,但是当我在 OptionsMenu 中选择某些内容时,它不再被调用
这是我的代码。
主要 Activity
private PopupMenu mPopupMenu;
ImageButton settings = findViewById(R.id.buttonSettings);
mPopupMenu = new PopupMenu(this, settings);
MenuInflater menuInflater = mPopupMenu.getMenuInflater();
menuInflater.inflate(R.menu.main_settings, mPopupMenu.getMenu());
settings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPopupMenu.show();
}
});
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_settings, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.menuNightMode) {
openDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
public void openDialog() {
DialogNightMode dialogNightMode = new DialogNightMode();
dialogNightMode.show(getSupportFragmentManager(), "test");
}
这是 Xml
<ImageButton
android:id="@+id/buttonSettings"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="17dp"
android:background="@color/transparent"
android:tint="@color/gray"
android:src="@drawable/ic_settings_black_24dp" />
菜单Xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/menuNightMode" android:title="@string/MainPageMenuNight" />
</menu>
请您参考如下方法:
您的代码缺少 MenuItemClickListener
,您需要将其设置为 PopupMenu
。
设置如下
popup.show();
//Set on click listener for the menu
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if(id == R.id.menuNightMode) {
openDialog();
}
return false;
}
});