leecade / react-native-practice

8 stars 0 forks source link

Avoiding the Keyboard #13

Closed leecade closed 8 years ago

leecade commented 8 years ago

image

UPDATE

New Keyboard api

http://facebook.github.io/react-native/releases/next/#the-keyboard-api

New feature: <KeyboardAvoidingView /> 8b78846

Detect when the keyboard is being shown.

// 0.27.2+
const { Keyboard } from 'react-native'
// Keyboard.addListener('KeyboardWillShow', func)

// 0.27.0 & 0.27.1
// const { Keyboard } from 'Keyboard'
// Keyboard.addListener('KeyboardWillShow', func)

// older
// const { DeviceEventEmitter } from 'react-native'
// DeviceEventEmitter.addListener('KeyboardWillShow', func)

keyboardDidShow = e => {
}

keyboardDidHide = e => {
}

componentWillMount () {
  this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow)
  this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide)
}

componentWillUnmount () {
  this.keyboardDidShowListener.remove()
  this.keyboardDidHideListener.remove()
}

for Android

insted of keyboardDidShow and keyboardDidHide

ref: https://github.com/facebook/react-native/issues/3468

Detect the keyboard height.

const keyboardHeight = e.endCoordinates.height

Resize the container by subtracting out the keyboard, and also resize any adaptive items, like logos.Animate accordingly.

keyboardDidShow = e => {
  let visibleHeight = Dimensions.get('window').height - e.endCoordinates.height
  this.setState({
    visibleHeight
  })
}

keyboardDidHide = e => {
  this.setState({
    visibleHeight: Dimensions.get('window').height
  })
}
render () {
  return (
    // Merge height into container style
    <View style={ [Styles.container, {height: this.state.visibleHeight}] }>
    </View>
  )
}

Animate accordingly

const { LayoutAnimation } from 'react-native'
keyboardDidShow (e) {
  // Animation types easeInEaseOut/linear/spring
  LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
  let visibleHeight = Dimensions.get('window').height - e.endCoordinates.height
  this.setState({
    visibleHeight
  })
}

keyboardDidHide (e) {
  // Animation types easeInEaseOut/linear/spring
  LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut)
  this.setState({
    visibleHeight: Dimensions.get('window').height
  })
}

Note that in order to get this to work on Android you need to set the following flags via UIManager

import { UIManager } from 'react-native'
UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true)

ref: https://github.com/facebook/react-native/blob/ebb85768b5c45f6ac8060a9d238cd2aca9f9138c/docs/Animations.md#layoutanimation

ref: https://github.com/Andr3wHur5t/react-native-keyboard-spacer

krns commented 8 years ago

Nice, this really helped me a lot!

leecade commented 8 years ago

finally: http://facebook.github.io/react-native/releases/0.34/docs/keyboardavoidingview.html#keyboardavoidingview