android - 如何更改菜单图标 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;
}
这是我onMessageReceived
的MyFirebaseMessagingService
@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);
}
推荐阅读
- python - 使用许多公式创建复杂字典的最佳实践
- postgresql - 如何聚合 JSONB PostgreSQL 10
- android - 领域 - java.lang.IllegalStateException:对象不再有效操作
- python - Tkinter 输入框值在 mongodb 中存储为 null
- powershell - 使用以下命令的 Powershell 自动化脚本可一次性更新
- macos - 在 osx 启动时执行交互过程
- excel - Vlookup 为一个用户 ID 返回多个值
- avi - 强制 .avi 和 .mkv 文件在浏览器中播放(而不是下载)
- linux - U-Boot:TI Sitara AM335X MII 连接到 Marvell 开关
- amazon-web-services - 通过 jenkins 部署到 AWS 时出现 Terraform 版本错误?