原文链接:https://blog.csdn.net/weixin_42865887/article/details/81366129
react-native默认没有keyEvent,这里主要介绍如何实现将keyEvent(按键事件或者遥控器事件)发送给页面:
native java代码
import android.view.KeyEvent;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class MainActivity extends ReactActivity {
private void sendEvent(ReactContext reactContext,
String eventName, @Nullable WritableMap params) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
ReactContext reactContext = getReactInstanceManager().getCurrentReactContext();
WritableMap params = Arguments.createMap();
params.putInt("which", event.getKeyCode());
if (event.getAction() == KeyEvent.ACTION_DOWN) {
sendEvent(reactContext, "keydown", params);
} else if (event.getAction() == KeyEvent.ACTION_UP) {
sendEvent(reactContext, "keyup", params);
}
return super.dispatchKeyEvent(event);
}
}