1. 程式人生 > >RN的文字框 獲取焦點但隱藏鍵盤 React Native TextInput onfocus but hide keyboard

RN的文字框 獲取焦點但隱藏鍵盤 React Native TextInput onfocus but hide keyboard

After a lot of research, I was able to find a monkey patch for this issue on Android (I’m currently developing an Android app only).

We should create a Native Module that calls InputMethodManager to close the keyboard when visible and add an onFocus function on our TextInput that calls the Native’s keyboard dismissal function.

Here’s how to do it:

Create a Keyboard Native Module
KeyboardModule.java
package com.xxx.xxx;

import android.app.Activity;
import android.view.inputmethod.InputMethodManager;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;

public class KeyboardModule extends ReactContextBaseJavaModule {

    public KeyboardModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "KeyboardFunctionalities";
    }

    @ReactMethod
    public void hideKeyboard() {
        final Activity activity = getCurrentActivity();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
    }
}

KeyboardPackage.java

package com.xxx.xxx;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class KeyboardPackage implements ReactPackage {

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(
            ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();

        modules.add(new KeyboardModule(reactContext));

        return modules;
    }

}

Register it in MainApplication.java

@Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            ...,
            new KeyboardPackage()
      );
    }

Use it in your React Native code:

import { TextInput, NativeModules } from "react-native"

render(){
  return(
    <TextInput onFocus={() => NativeModules.KeyboardFunctionalities.hideKeyboard() } />
  )
}