archangel archangel - 6 months ago 80
Android Question

android 4.4 ionic hardware button back close keyboard

I used ionic framework and build a app in android 4.4.
when I put a input field on some view, and make focus in it, the keybord is showing,but when I press the hardware back button, I want it to hide the keyboard,but it close the current view and go back history view, how can I let it to hide keyboard and don`t to close the current view page? If the focus not in the input field,then press back button let it to close current view is normal.

$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
// StatusBar.styleDefault();
StatusBar.styleBlackOpaque();
}
});
$ionicPlatform.registerBackButtonAction(function (e) {
e.preventDefault();
console.log("aaaaaa:"+$cordovaKeyboard.isVisible());
function showConfirm() {
var confirmPopup = $ionicPopup.confirm({
title: '<strong>exit?</strong>',
template: 'exit?',
okText: 'exit',
cancelText: 'cancel'
});
confirmPopup.then(function (res) {
if (res) {
ionic.Platform.exitApp();
} else {

}
});
}

if ($location.path() == '/app/home') {
showConfirm();
} else
if ($ionicHistory.backView()) {

if($cordovaKeyboard.isVisible()) {
$cordovaKeyboard.close();
} else {
$ionicHistory.goBack();
}
} else {
showConfirm();
}
return false;
}, 101);


$cordovaKeyboard.isVisible() is alway return false in $ionicPlatform.registerBackButtonAction().

Answer

Ok,I find a solution about that question.

window.addEventListener('native.keyboardhide', keyboardHideHandler);
        function keyboardHideHandler(e){
          var test=$ionicPlatform.registerBackButtonAction(function (e) {
          },1000);
            $timeout(function() {
              test();
            }, 100);
        }

I know this method is not best practice, but it can work. If someone find more better method or this method production some bugs, please let me know.