简体   繁体   中英

Keyboard hides content for Android React Native webview

I am using React Native's <WebView> component.

The documentation has no mention of how to handle the keyboard hiding the webview when the webview's HTML contains an <input> which becomes focused on in Android.

Has anyone managed to solve this? I have found a library that seems to work for regular <View> , but not a <WebView> .

you can wrap your WebView with a KeyboardAvoidingView

  <KeyboardAvoidingView
    behavior={Platform.select({ ios: "position", android: null })}
    enabled
    contentContainerStyle={{ flex: 1 }}
    keyboardVerticalOffset={Platform.select({ ios: offset, android: 20 })}
    style={{ flexGrow: 1 }}
  >
    <WebView/>
  </KeyboardAvoidingView>

Have you thought about responding to system level events for the keyboard appearing and disappearing, then adjusting the WebView size appropriately?

There is an old question about how to handle this, it may or may not still be relevant. This answer in particular shows how to handle keyboard events. https://stackoverflow.com/a/33585501/1403

DeviceEventEmitter.addListener('keyboardDidShow',(frames)=>{
  if (!frames.endCoordinates) return;
  this.setState({keyboardSpace: frames.endCoordinates.height});
});
DeviceEventEmitter.addListener('keyboardWillHide',(frames)=>{
  this.setState({keyboardSpace:0});
});

You could use the frames.endCoordinates.height value to alter the height of your WebView, ensuring that the content is not hidden behind the keyboard.

Just raising awareness that this can also be simply achieved by using react-native-keyboard-spacer if you are not in for intricate keyboard control.

import KeyboardSpacer from 'react-native-keyboard-spacer';

class DemoApp extends Component {
  render() {
    return (
      <View>
        <WebView ... />
        <KeyboardSpacer/>
      </View>
    );
  }
}

I used WebView.onTouchStart and ScrollView.scrollTo. This is work like charm for me.

import { useRef } from "react";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp
} from "react-native-responsive-screen";

const scrollRef = useRef();

const scrolldown = () => {
   scrollRef.current.scrollTo((wp("100%") * 2) / 3);
};

<ScrollView ref={scrollRef} >
...

<WebView onTouchStart={scrolldown} >
...

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