ECourant
ECourant

Reputation: 108

Toggle hiding of soft keyboard programatically

We have an application that runs on a barcode scanner android device (ScanSKU). And whenever the user is scanning anything the keyboard will show up as it "types" the text they scanned, and will block half of the screen.

Our application is basically a WebView and we still need to be able to focus form elements inside of it.

But is there anyway we can build a toggle to disable the on-screen keyboard from coming up while they are in the WebView?

I've tried using this:

// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

From: Close/hide the Android Soft Keyboard

But with no success.

Any suggestions or ideas on how I can go about this?

Upvotes: 0

Views: 255

Answers (1)

Victor V.
Victor V.

Reputation: 328

There is another way how to get focus view, getCurrentFocus method didn't work for me too. Try this solution, you should provide instance of Activity object.

public static void hideSoftKeyboard(Context context) {
    try {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(((Activity) context).getWindow().getDecorView().getRootView().getWindowToken(), 0);
        ((Activity) context).getWindow().getDecorView().getRootView().clearFocus();
    } catch (NullPointerException e) {
        // some error log 
    }
}

Edited: If you use WebView and still need to be able to focus form elements inside of it. You can set attribute

view.setFocusableInTouchMode(false);

for another views on the screen and WebView will hold focus on it.

Upvotes: 2

Related Questions