IONIC Keyboard hide on input focus

2019-05-11 22:08发布

问题:

I'm writing an Ionic app that will be used for logistic purposes in the Healthcare sector.
The devices that will be used for this app have a build-in barcode scanner and run on android 4.1.1.
This scanner inputs data within a input field and submits it by pressing the "enter" key. Due to the scanner being the my "keyboard" in certain situations I want to hide the keyboard on input focus or click.

I wrote the following directive using the ionic keyboard cordova plugin:

directives.directive("showKeyboard", [
function()  {
    var linkFn = function(scope, element, attrs) {
        console.log(scope);
        console.log(element);
        console.log(attrs);
        if(!window.cordova || !window.cordova.plugins.Keyboard) return; // Check for cordova keyboard plugin

        if(element[0].nodeName.toLowerCase() != 'input') return; // check for input

        if(attrs.type.toLowerCase() != 'password' && attrs.type.toLowerCase() != 'text') return; // check for type of input

        element.bind("focus click",
            function(e) {
                e.preventDefault();
                if(scope.$eval(attrs.showKeyboard)){
                    console.log('show')
                    window.cordova.plugins.Keyboard.show();
                }
                else    {
                    console.log('hide');
                    cordova.plugins.Keyboard.close();

                }
            }
        );
    };

    var keyboardDirective = {
        restrict : 'A',
        link: linkFn
    };

    return keyboardDirective;

}
]);  

Function seems to work. Only the keyboard won't close and seems to be "forced" to open by the device.

any suggestions?

回答1:

I tried using your directive to suppress the default native keyboard in order to show an alternative keyboard and found that I had to use a $timout of 100ms before calling hide for the keyboard to close (to work around the race condition). However, it's creating a flicker artifact so it's not the best solution. Another idea which I haven't yet tried is to suppress they keyboard on the Android side in Java via a custom plugin which would call,

InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);