使用Android uiautomator设置文本后禁止键盘

时间:2013-06-20 20:35:44

标签: android uiautomator

使用uiautomator for Android我可以在文本字段中设置文本,但无法关闭键盘。对于一些处于lanscape模式的手机,键盘会占据整个屏幕,并且必须点击“完成”以退出该视图。如果我可以压制键盘,那么我可以在横向和纵向上运行uiautomator而没有问题。

new UiObject(new UiSelector().text("Enter Text")).click();
new UiObject(new UiSelector().className("android.widget.EditText").instance(0)).setText("sample text");

// This is where I need to suppress the keyboard to view the app instead of just the keyboard itself.

new UiObject(new UiSelector().text("Submit")).click();

提前致谢。

6 个答案:

答案 0 :(得分:4)

这是一个相当古老的问题但是使用UiAutomator 2.0可以正确而完整地回答这个问题,因此就是这样。

最佳选择是:

if(isKeyboardOpened()){
    UiDevice.pressBack();
}

但到目前为止,问题是如何实现isKeyboardOpened()。

由于UiAutomator 2.0基于仪器,因此我们可以访问UiAutomation,我们可以验证屏幕上是否有任何输入窗口:

boolean isKeyboardOpened(){
    for(AccessibilityWindowInfo window: InstrumentationRegistry.getInstrumentation().getUiAutomation().getWindows()){
        if(window.getType()==AccessibilityWindowInfo.TYPE_INPUT_METHOD){
            return true;
        }
    }
    return false;
}

答案 1 :(得分:3)

似乎非常错误,但它完成了工作。

public static final int KEYBOARD_WAIT_TIME = 111;

Espresso.closeSoftKeyboard();
sleep(AutomatedTestConfig.KEYBOARD_WAIT_TIME);

答案 2 :(得分:1)

通常单击后退键将关闭键盘。

getUiDevice().pressBack();

答案 3 :(得分:1)

我使用了你的代码,只是在插入文本的末尾添加了\ n。这模拟'enter',但键盘仍然出现,所以你需要pressBack()来关闭keyb。

new UiObject(new UiSelector()
   .className("android.widget.EditText")
   .instance(0))
   .setText("sample text\n");
getUiDevice().pressBack();

有更优雅的解决方案:

new UiObject(new UiSelector()
   .className("android.widget.EditText")
   .instance(0))
   .setText("sample text");
getUiDevice().pressEnter();

答案 4 :(得分:0)

经过大量的工作后,我发现了按照这样做的方式。 问题是如果没有显示软键盘,调用getUIDevice().pressBack()会破坏测试。

InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isAcceptingText()) {
    getUIDevice().pressBack();
}

只有在显示键盘时才会按下。

答案 5 :(得分:-1)

尝试DummyIME并使用uiautomator选项运行-e disable_ime true工具。 DummyIME位于Android git repository

  1. 克隆DummyIME的源代码:

    git clone https://android.googlesource.com/platform/frameworks/testing
    
  2. 构建并安装DummyIME(您可以更改android-18):

    cd testing/uiautomator/utils/DummyIME
    android update project -p . -t android-18
    ant clean debug install
    
  3. 使用带有-e disable_ime true选项的uiautomator框架运行测试。

    adb shell uiautomator runtest <JARS> -e disable_ime true -c <CLASSES> 
    
  4. 请注意,您必须在已测试的设备中恢复默认IME的设置 因为在运行测试后它会自动更改为DummyIME

相关问题