美文网首页React Native 踩坑合集
「React Native」Android返回键监听

「React Native」Android返回键监听

作者: Android埋坑的艺术 | 来源:发表于2017-12-19 17:14 被阅读62次

    在需要做监听的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返回键监听

        本文链接:https://www.haomeiwen.com/subject/yhriwxtx.html