Search code examples
react-nativenative-base

How to use KeyboardAvoidingView in full screen mode?


enter image description here

The above yellow colored area is Textarea and a panel of buttons expected to stick to bottom of screen all the time. However when user trying to type, Keyboard will block the view as shown below

enter image description here

I've implemented KeyboardAvoidingView but it failed to make the button appear above of keyboard.

My code is as below:

  <KeyboardAvoidingView behavior="padding" style={{ flex: 1 }}>
    <Container style={Styles.containerStyle}>
      <Textarea 
        autoCapitalize="none"
        autoCorrect={false}
        style={Styles.textAreaStyle}
      />
      <View style={Styles.buttonPanelStyle}>
        <Button style={Styles.buttonStyle}><Text>CANCEL</Text></Button>
        <Button style={Styles.buttonStyle}><Text>SAVE</Text></Button>
      </View>
    </Container>
  </KeyboardAvoidingView>


const Styles = StyleSheet.create({
  containerStyle: { backgroundColor: 'green' },
  textAreaStyle: { backgroundColor: 'yellow', flex: 1 },
  buttonPanelStyle: { backgroundColor: 'red', flexDirection: 'row' },
  buttonStyle: { flex: 1, justifyContent: 'center' }
});

Solution

  • I've found a way to get around with it. Wrapped the KeyboardAvoidingView with an extra View, and implement onLayout to recalculate the height of screens. Sample code as below:

    const { height: fullHeight } = Dimensions.get('window');
    
    onLayout = ({
      nativeEvent: { layout: { height } },
    }) => {
      const offset = fullHeight - height;
      this.setState({ offset });
    }
    
    <View style={{ flex: 1 }} onLayout={this.onLayout}>
      <KeyboardAvoidingView behavior="padding" style={{ flex: 1 }} keyboardVerticalOffset={this.state.offset}>
        ...
      </KeyboardAvoidingView>
    </View>