这是我设置工具栏 (MainActivity) 的方法。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
现在我想在收到通知时将 xml 文件更改为 main_notification_on
。这就是我要实现的目标
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(there is no new notification)
{
getMenuInflater().inflate(R.menu.main, menu); }
else{
getMenuInflater().inflate(R.menu.main_notification_on, menu);
}
return true;
}
这是来自 MyFirebaseMessagingService
的我的 onMessageReceived
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title = remoteMessage.getData().get("title");
String message = remoteMessage.getData().get("body");
showNotifications(title, message);
}
提前致谢。
最佳答案
您可以将名为 invalidateOptionsMenu() 的东西与 OnPrepareOptionsMenu() 一起使用。每当调用 invalidateOptionsMenu() 时,回调中的 OnPrepareOptionsMenu() 将被调用。您可以在此处更改菜单布局。代码是这样的:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title = remoteMessage.getData().get("title");
String message = remoteMessage.getData().get("body");
showNotifications(title, message);
//send a broadcast from here and catch it in MainActivity
}
现在在 MainActivity 的广播接收器的 OnReceive() 中使用 invalidateOptionsMenu():
@Override
OnReceive(){
invalidateOptionsMenu();
}
覆盖 MainActivity 中的 OnPrepareOptionsMenu() 方法并更改那里的布局。这些方面的内容:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_notification_on, menu);
return super.onPrepareOptionsMenu(menu);
}
关于android - 如何更改菜单图标 onMessageReceived,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52700360/