我有问题。我需要动态更改选项菜单项图标,但我尝试的所有内容似乎都不起作用。我正在使用android的兼容性库,我正在调用supportInvalidateOptionsMenu。我已经覆盖了onPrepareOptionsMenu,因为这是根据文档的正确方法。但每次我调用supportInvalidateOptionsMenu时,onCreateOptionsMenu总是在onPrepareOptionsMenu之前调用。这是怀疑吗?这是我的代码:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem actionNote = menu.findItem(R.id.action_note);
db.open();
int notesCount = db.getNotificationsCount(CurrentConnection.username);
db.close();
switch (notesCount) {
case 0:
actionNote.setIcon(R.drawable.notify_icon);
break;
case 1:
actionNote.setIcon(R.drawable.notify_icon1);
actionNote.setVisible(false);
break;
case 2:
actionNote.setIcon(R.drawable.notify_icon2);
break;
case 3:
actionNote.setIcon(R.drawable.notify_icon3);
break;
default:
actionNote.setIcon(R.drawable.notify_icon3m);
break;
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
MenuItem action_note = menu.findItem(R.id.action_note);
db.open();
int notesCount = db.getNotificationsCount(CurrentConnection.username);
db.close();
switch (notesCount) {
case 0:
action_note.setIcon(R.drawable.notify_icon);
break;
case 1:
action_note.setIcon(R.drawable.notify_icon1);
break;
case 2:
action_note.setIcon(R.drawable.notify_icon2);
break;
case 3:
action_note.setIcon(R.drawable.notify_icon3);
break;
default:
action_note.setIcon(R.drawable.notify_icon3m);
break;
}
return true;
}
我在:
中调用supportInvalidateOptionsMenu PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
CurrentConnection.connection.addPacketListener(new PacketListener() {
@Override
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String[] fields = message.getBody().split(":");
String subject = fields[1];
int type = Integer.parseInt(fields[2]);
String sender_username = fields[3];
String sender_name = fields[4], receiver_username = fields[5], receiver_name = fields[6];
db.open();
db.insertNotification(sender_username, sender_name,
receiver_username, receiver_name, subject, type);
db.close();
supportInvalidateOptionsMenu();
}
}
}, filter);
这只是来自asmack libray(一个XMPP客户端库)的监听器。我需要帮助。
答案 0 :(得分:0)
实际上答案很简单。 PacketListener在另一个线程中运行,因此无法从中更新UI。只需要使用处理程序在处理程序中调用supportInvalidateOptionsMenu。
messagesHandler.post(new Runnable() {
@Override
public void run() {
PublicChatFragment publicChatFragment = (PublicChatFragment) getSupportFragmentManager()
.findFragmentByTag(PublicChatFragment.TAG);
publicChatFragment.setAdapter();
}
});
在UI线程中创建messagesHandler,以解决问题。