简体   繁体   中英

React native android keyboard events

I've been trying to create a custom react native custom keyboard events. Specifically, I've been trying to detect the backspace key.

In my MainApplication.java

public boolean onKeyUp(int keyCode, KeyEvent event) {

  // Filter for delete key being pressed
  if (event.getAction() == KeyEvent.DEL) {
    getReactNativeHost().getReactInstanceManager().getCurrentRea‌​ctContext()
    .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
    .emit("onKeyPressed", keyCode);
  }
  return true;
}

In my react component

componentDidMount() {
  if (Platform.OS === 'android') {
    DeviceEventEmitter.addListener('onKeyPressed', this.handleKeyPress);
  }
}

componentWillUnmount() {
    if (Platform.OS === 'android') {
      DeviceEventEmitter.removeListener('onKeyPressed');
    }
}

Can someone give me some ideas as to why are the events not being fired?

Upon doing a bit more research into android development.

Using Keyevents to detect key pressed is not reliable.

https://developer.android.com/reference/android/view/KeyEvent.html

As soft input methods can use multiple and inventive ways of inputting text, there is no guarantee that any key press on a soft keyboard will generate a key event: this is left to the IME's discretion, and in fact sending such events is discouraged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM