onPrepareOptionsMenu被触发但是menuItem没有更新

时间:2015-12-09 03:10:04

标签: android android-layout

它应该根据蓝牙连接改变图标/标题,但是 它仅在我点击overFlow菜单(3dots)时才有效,然后立即改变

public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem menuItem = menu.findItem(R.id.menu_connect); 
    if (mChatService != null && mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
        Log.d(TAG, "onPrepareOptionsMenu.STATE_CONNECTED");
        menuItem.setIcon(R.drawable.bt_wave_conn_128x128);
        // menuItem.setTitle("Connected");
    } else {
        Log.d(TAG, "onPrepareOptionsMenu.NOT_CONNECTED");
        //menuItem.setTitle("BluetoothConnect");
        menuItem.setIcon(R.drawable.bt_conn128x128pink);
    }
    return true;
}

logcat的

12-09 02:17:01.920 17637-17637/com.example.marrek.megaphmbt D/MainActivity: - ON RESUME -
    12-09 02:17:01.925 17637-17637/com.example.marrek.megaphmbt I/MainActivity: MESSAGE_STATE_CHANGE: 1
    12-09 02:17:01.973 17637-17637/com.example.marrek.megaphmbt D/MainActivity: onPrepareOptionsMenu.NOT_CONNECTED
    12-09 02:17:02.044 17637-17637/com.example.marrek.megaphmbt I/MainActivity: MESSAGE_STATE_CHANGE: 2
    12-09 02:17:02.087 17637-17637/com.example.marrek.megaphmbt D/MainActivity: onPrepareOptionsMenu
    12-09 02:17:02.087 17637-17637/com.example.marrek.megaphmbt D/MainActivity: onPrepareOptionsMenu.STATE_CONNECTED
    12-09 02:23:26.287 17637-17637/com.example.marrek.megaphmbt D/MainActivity: onPrepareOptionsMenu
    12-09 02:23:26.287 17637-17637/com.example.marrek.megaphmbt D/MainActivity: onPrepareOptionsMenu.STATE_CONNECTE

所以我试过toolbar.showOverflowMenu(); and toolbar.hideOverflowMenu(); 但没有成功:/任何想法如何强制menuItem更改图标/标题?

设备是联想平板电脑安卓5.1

1 个答案:

答案 0 :(得分:0)

首先,您必须致电invalidateOptionsMenu()以请求系统调用onPrepareOptionsMenu()

试试这个:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem menuItem = menu.findItem(R.id.menu_connect); 
    if (mChatService != null && mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
        Log.d(TAG, "onPrepareOptionsMenu.STATE_CONNECTED");
        menuItem.setIcon(R.drawable.bt_wave_conn_128x128);
        // menuItem.setTitle("Connected");
    } else {
        Log.d(TAG, "onPrepareOptionsMenu.NOT_CONNECTED");
        //menuItem.setTitle("BluetoothConnect");
        menuItem.setIcon(R.drawable.bt_conn128x128pink);
    }
    menu.clear();
    menu.add(0, Your menu Item, 0, "False/True");

    return super.onPrepareOptionsMenu(menu);
}