如何使用浓缩咖啡在SearchView上键入文本

Mig*_*Slv 2 android searchview android-espresso

TypeText似乎不适用于SearchView

onView(withId(R.id.yt_search_box))
            .perform(typeText("how is the weather?"));
Run Code Online (Sandbox Code Playgroud)

给出错误:

在视图“ ID为:../ yt_search_box”的视图中执行“键入文本(天气如何?)”时出错

Mig*_*Slv 7

对于任何也遇到此问题的人,解决方案是为SearchView类型编写ViewAction,因为typeText仅支持TextEditView。

这是我的解决方案:

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);
        }
    };
}
Run Code Online (Sandbox Code Playgroud)


hye*_*ena 7

@MiguelSlv 上面的回答,转换为 kotlin

fun typeSearchViewText(text: String): ViewAction {
    return object : ViewAction {
        override fun getDescription(): String {
            return "Change view text"
        }

        override fun getConstraints(): Matcher<View> {
            return allOf(isDisplayed(), isAssignableFrom(SearchView::class.java))
        }

        override fun perform(uiController: UiController?, view: View?) {
            (view as SearchView).setQuery(text, false)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Cés*_*eña 5

这对我有用:

onView(withId(R.id.search_src_text)).perform(typeText("how is the weather?"))
Run Code Online (Sandbox Code Playgroud)

  • 下次你应该给出更多解释为什么你的解决方案应该有效。乍一看,我认为它与问题中的代码相同,但事实并非如此:D。密钥是使用 R.id.search_src_text 的 ID,它访问通过单击您自己的视图打开的视图。 (2认同)