Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Espresso typeText into EditText in ActionBar

I have a SearchView in my ActionBar that is inflated from XML

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_menu_search"
        android:showAsAction="always|collapseActionView"
        android:icon="@drawable/action_bar_search_icon"
        android:actionViewClass="android.widget.SearchView"/>
</menu>

I inflate it in my Fragment this way:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.search, menu);

    final MenuItem item = menu.findItem(R.id.action_menu_search);
    searchView = (SearchView) item.getActionView();
    searchView.setOnQueryTextListener(this);
}

And my test:

onView(withId(R.id.catalog_filter_indicator_header_text)).perform(click());

//enter text and wait for suggestions
onView(withId(R.id.action_menu_search)).perform(click());
onViewisAssignableFrom(AutoCompleteTextView.class)).perform(click(), typeText("test"));

It looks like that field looses focus when it starts typing. And I don't know why.

All views are found and typeText statement passes without a hitch, but text does not appear in the field. I also tried that with simple EditText and custom android:actionLayout but with the same results.

Is there something I'm missing?

like image 348
Martynas Jurkus Avatar asked Jul 24 '14 07:07

Martynas Jurkus


2 Answers

This code works for the SerachView in my ActionBar, as the SearchView is the only EditText in my Fragment :

onView(withId(R.id.action_search)).perform(click());    
onView(isAssignableFrom(EditText.class)).perform(typeText("test"), pressKey(KeyEvent.KEYCODE_ENTER));

KeyEvent.KEYCODE_ENTER is the code for pressing the submit button.

like image 122
JensJensen Avatar answered Nov 09 '22 22:11

JensJensen


Search view has default id. You can get it in Espresso in this way.

onView(withId(androidx.appcompat.R.id.search_src_text)).perform(typeText("example"), pressKey(KeyEvent.KEYCODE_ENTER));

Prior to AndroidX, the ID was android.support.design.R.id.search_src_text

Hope this was useful.

like image 40
Lorenzo Camaione Avatar answered Nov 09 '22 22:11

Lorenzo Camaione