How to type text on a SearchView using espresso

こ雲淡風輕ζ 提交于 2020-01-13 19:19:29

问题


TypeText doesn't seem to work with SearchView.

onView(withId(R.id.yt_search_box))
            .perform(typeText("how is the weather?"));

gives the error:

Error performing 'type text(how is the weather?)' on view 'with id:../yt_search_box'


回答1:


For anyone that bump into this problem too, the solution is to write a ViewAction for the type SearchView, since the typeText only supports TextEditView

Here my solution:

public static ViewAction typeSearchViewText(final String text){
    return new ViewAction(){
        @Override
        public Matcher<View> getConstraints() {
            //Ensure that only apply if it is a SearchView and if it is visible.
            return allOf(isDisplayed(), isAssignableFrom(SearchView.class));
        }

        @Override
        public String getDescription() {
            return "Change view text";
        }

        @Override
        public void perform(UiController uiController, View view) {
            ((SearchView) view).setQuery(text,false);
        }
    };
}



回答2:


you can use Resource#getSystem to get the View

Resources.getSystem().getIdentifier("search_src_text",
    "id", "android")


onView(withId(Resources.getSystem().getIdentifier("search_src_text",
"id", "android"))).perform(clearText(),typeText("enter the text"))
.perform(pressKey(KeyEvent.KEYCODE_ENTER))


来源:https://stackoverflow.com/questions/48037060/how-to-type-text-on-a-searchview-using-espresso

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!