Wednesday, October 21, 2015

Hide Soft Keyboard in Android Emulator/Device

There are multiple strategies for hiding the keyboard:

Method -1
There is a direct method available in AndroidDriver (or if you are using appium for mobile test automation, this method is availale in AppiumDriver too)
For example,
AndroidDriver<WebElement>  driver = new AndroidDriver<WebElement>(
    new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.hideKeyboard();

Method-2
You can hide soft keyboard completely(or only for some test specific) by passing the following property to the desired capabilities as below:
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("unicodeKeyboard", "true");

Method-3
You can hide by clicking different android keys like "Done" or "Back". Here is an example of hiding soft keyboard using BACK key.
driver.pressKeyCode(AndroidKeyCode.BACK);
In some older versions of AndroidDriver you can find below method
((AndroidDriver) driver).sendKeyEvent(AndroidKeyCode.BACK);

Method-4
You can go back by using following code, which will hide your soft keyboard
driver.navigate().back();
This you need to call only after entering text into edit field. For some views or activities, it may go back to the previous activity.

Method-5
You may try the below if it works for you. In some cases this doesn't work well.
HashMap keycode = new HashMap();
keycode.put("keycode", 4);
((JavascriptExecutor)driver).executeScript("mobile: keyevent", keycode);
Method-6
If you have android application code base integrated with your android test base, you can use the below code which will perform based on your current activity.
public void hideSoftKeyboard(Activity activity) {
  InputMethodManager imm = (InputMethodManager)
  activity.getSystemService(Context.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

3 comments:

  1. Method-2 worked very well for hiding soft keyboard completely
    Thanks

    ReplyDelete
  2. Awesome post!

    ReplyDelete
  3. "Great blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.php jobs in hyderabad.
    "

    ReplyDelete