LoginSignup
7
4

More than 5 years have passed since last update.

【React Native】TextInputでキーボードが押し上げられる【Android】

Last updated at Posted at 2019-03-17

現象

  • androidのとき
  • TextInputを使用する
  • 画面の要素がキーボードの上にひっついてくる

badKeyboardAndroid.gif

対応

anrdoird/app/src/mainの以下の部分を修正する

-        android:windowSoftInputMode="adjustResize">
+        android:windowSoftInputMode="adjustPan">

結果

badKeyboardAndroidSuccess.gif

その他

KeyboardAvoidingViewではうまくいかないときもあるみたいです。
上記の変更を行わなくても、各pageのJS側の設定でも対応できます。

react-navigationのタブで発生したとき

この例はreact-navigationのbottomTabで発生したものです。
基本的にanrdoir/app/src/mainを修正したほうが正しい対応のように見えます。

1. TabComponentを作る

Keyboard.addListenerを使って、キーボードの判定を行い、都度制御しています。

import React, { Component } from 'react';
import { Platform, Keyboard } from 'react-native';
import { BottomTabBar } from 'react-navigation-tabs';

 // AndroidがキーボードによってtabBarを押し上げるのを防ぐ
// https://github.com/react-navigation/react-navigation-tabs/issues/16#issuecomment-402557546
export default class TabBarComponent extends Component<{}> {
  state = {
    visible: true,
  };

   componentDidMount() {
    if (Platform.OS === 'android') {
      this.keyboardEventListeners = [
        Keyboard.addListener('keyboardDidShow', this.visible(false)),
        Keyboard.addListener('keyboardDidHide', this.visible(true)),
      ];
    }
  }

   componentWillUnmount() {
    this.keyboardEventListeners &&
      this.keyboardEventListeners.forEach(eventListener =>
        eventListener.remove(),
      );
  }

   visible = visible => () => this.setState({ visible });

   render() {
    if (!this.state.visible) {
      return null;
    }
    return <BottomTabBar {...this.props} />;
  }
}

2. 1で作ったComponentをTabOptionにtabBarComponentを設定します

  {
    tabBarPosition: 'bottom',
    initialRouteName: PATH.XXX,
+   tabBarComponent: props => <TabBarComponent {...props} />,
    tabBarOptions: {
      activeTintColor: 'red',
      labelStyle: {},
      style: {},
    },
  },

ソースもと

Bottom tab bars and keyboard on Android
https://github.com/react-navigation/react-navigation-tabs/issues/16

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4