当Handler获取消息时,更改MenuItem标题和图标

时间:2013-02-11 10:29:39

标签: android actionbarsherlock handler menuitem

我想在连接状态发生变化时更改标题和图标... updateMenuTitle() is from here之所以有效,是因为我测试了它,但是当我从处理程序调用{​​{1}}应用程序时,应用程序崩溃时无法正常工作

updateMenuTitle()

解决方案:

 private void updateMenuTitle(int x) {
    MenuItem btstatus = menu.findItem(R.id.btstatus);
    if (x == 1) {
        btstatus.setTitle("Connected");
        btstatus.setIcon(R.drawable.ic_btstatus_on);
    } else if (x == 2){
        btstatus.setTitle("Connecting");
        btstatus.setIcon(R.drawable.ic_btstatus_idle);
    }else if (x == 0){
        btstatus.setTitle("Disconnected");
        btstatus.setIcon(R.drawable.ic_btstatus_off);
    }
}

private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case MESSAGE_STATE_CHANGE:
            switch (msg.arg1) {
            case BluetoothRfcommClient.STATE_CONNECTED:
                mTxtStatus.setText(R.string.title_connected_to);
                mTxtStatus.append(" " + mConnectedDeviceName);
                updateMenuTitle(1);//not working if I call it from here... app force close
                break;
            case BluetoothRfcommClient.STATE_CONNECTING:
                mTxtStatus.setText(R.string.title_connecting);
                updateMenuTitle(2);//not working if I call it from here... app force close
                break;
            case BluetoothRfcommClient.STATE_NONE:
                mTxtStatus.setText(R.string.title_not_connected);
                updateMenuTitle(0);//not working if I call it from here... app force close
                break;
            }
            break;
            .......

2 个答案:

答案 0 :(得分:0)

你可以为此实现onPrepareOptionMenu(),因为这是更高效的用户打开选项菜单,你可以显示带有标题和图标的必需菜单。

检查此示例

http://thedevelopersinfo.wordpress.com/2009/10/20/dynamically-change-options-menu-items-in-android/

答案 1 :(得分:0)

我做了一点点不同:

private boolean flag = false;

void someMethod() {

   flag = true;
   invalidateOptionsMenu();

}

public boolean onCreateOptionsMenu (Menu menu) {

    if (flag) {
      // inflate menu 1
    } else {
      // inflate menu 2
    }

}

通过这种方式,您无需处理消息或其他内容。您只需要管理onCreateOptionsMenu上的菜单项。