Search code examples
androidreact-nativetouchableopacityreact-native-stylesheet

Rotated TouchableOpacity crashes on Android when selected


I rotate a TouchableOpacity (without any animation) as this:

transform: [
  { rotate: '45deg' }
]

It works fine on iOS, but crashes on Android (see tested versions below):

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double

I can't put a Double on rotate, as I get a Invariant violation. What can I do?


Environment :

  • OS: macOS High Sierra 10.13.5
  • Node: 7.10.0
  • Yarn: 1.9.4
  • npm: 4.2.0
  • Watchman: 4.9.0
  • Xcode: Xcode 9.4.1 Build version 9F2000
  • Android Studio: 3.2 AI-181.5540.7.32.5014246

Packages:(wanted => installed)

  • react: 16.3.1 => 16.3.1
  • react-native: 0.55.1 => 0.55.1

Tested on:

  • iOS 12 (worked fine on device and simulator)
  • Android 7.0 and 8.1 (both device and emulator)

Direct reference to this issue on Github


Solution

  • Conditionally use radians with Platform, they'll get converted to double without error:

    import {Platform} from 'react-native'
    …
    transform: [
      {rotate: (Platform.OS === 'ios') ? '45deg' : (3.14159/4)+'rad'}
    ]
    

    This will then display fine.

    But, that rotated TouchableOpacity loses its touchable behavior by the way.

    To fix this, use a child view to apply your rotation on :

    <TouchableOpacity onPress={…}>
      <View style={styles.yourRotation}>
         …
      </View>
    </TouchableOpacity>