javagoogle-chrome-os

dispatchKeyShortcutEvent not being called in a Chrome OS environment


I want to implement code to react to common shortcuts like Ctrl + S (save), Ctrl + Z (undo) in a Chrome OS environment.

I have added the following code in the activity:

@Override
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
  if (event.getKeyCode() == KeyEvent.KEYCODE_O) {
      openFile(); // Ctrl+O, Shift+O, Alt+O
      return true;
  } else if(event.getKeyCode() == KeyEvent.KEYCODE_Z) {
      if (event.isCtrlPressed()) {
              undoLastAction();
              return true;
      }
  }
  return super.dispatchKeyShortcutEvent(event);
}

And I have added the Window.Callback to the activity:

public class ScMain extends AppCompatActivity implements View.OnClickListener,      
        FragmentManager.OnBackStackChangedListener, Window.Callback {

Android Studio displays the following message:

ComponentActivity.dispatchKeyShortcutEvent can only be called from within the same library group prefix (referenced groupId=androidx.core with prefix androidx from groupId=[my app])

Although the code compiles without error, the dispatchKeyShortcutEvent method is never called.

I can not find which dependency I should add in my gradle file. Or do I need additional code?


Solution

  • I solved this issue by using onKeyShortcut instead

    @Override
    public boolean onKeyShortcut (int keyCode, KeyEvent event) {
        if (event.isCtrlPressed()) {
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_Z:
                    UndoBtnFired(undoBtn);
                    break;
                case KeyEvent.KEYCODE_S:
                    saveToFile(null);
                    break;
                case KEYCODE_L:
                    clearDrawnLinks(mContext);
                    break;
                default:
                    break;
            }
        }
    
        return true;
    }