「React Native」Android返回键监听

在需要做监听的js中添加

    componentWillMount() {
        if (Platform.OS === 'android') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackHandler);
        }
    }

    componentWillUnmount() {

        if (Platform.OS === 'android') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackHandler);
        }
    }
    
    onBackHandler = () => {
        // this.onMainScreen and this.goBack are just examples, you need to use your own implementation here
        // Typically you would use the navigator here to go to the last state.
        if (!this.onMainScreen()) {
            this.goBack();
            return true;
        }
        return false;
    };

RN的容器Activity实现DefaultHardwareBackBtnHandler接口

    public class XXXActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
        //...
        private ReactInstanceManager mReactInstanceManager;
    
        @Override
        public void invokeDefaultOnBackPressed() {
            if (mReactInstanceManager != null) {
                mReactInstanceManager.onBackPressed();
            } else {
                super.onBackPressed();
            }
        }
        //...
    }

RN的容器为Fragment时,DefaultHardwareBackBtnHandler没起作用

这时我们需要在该Fragment中添加接收返回事件的代码

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (mReactInstanceManager != null) {
            switch (keyCode) {
                //...
                case KeyEvent.KEYCODE_BACK: {
                    mReactInstanceManager.onBackPressed();
                    return true;
                }
            }
        }
        return false;
    }

并且在Activity中向该Fragment注入onkeyUp事件

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return fragment.onKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
    }

你可能感兴趣的:(「React Native」Android返回键监听)