首页 > 解决方案 > 如何更改菜单图标 onMessageReceived

问题描述

这是我设置工具栏(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;
        }

这是我onMessageReceivedMyFirebaseMessagingService

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
     String title = remoteMessage.getData().get("title");
     String message = remoteMessage.getData().get("body");
     showNotifications(title, message);
}

提前致谢。

标签: androidfirebasefirebase-cloud-messaging

解决方案


您可以将名为 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);
}

推荐阅读