Skip to content

Instantly share code, notes, and snippets.

@Sloy
Created August 17, 2016 08:49
Show Gist options
  • Save Sloy/7dc24d9fe3e61969751a96da5be67313 to your computer and use it in GitHub Desktop.
Save Sloy/7dc24d9fe3e61969751a96da5be67313 to your computer and use it in GitHub Desktop.
Custom Espresso action for AutoCompleteTextView. It replaces the text without showing the annoying popup in your tests.
public class AutocompleteViewActions {
public static ViewAction replaceAutocomplete(@Nonnull String stringToBeSet) {
return actionWithAssertions(new ReplaceAutocompleteTextAction(stringToBeSet));
}
/**
* This is based on {@link ReplaceTextAction}
* with modifications thanks to "http://www.grokkingandroid.com/how-androids-autocompletetextview-nearly-drove-me-nuts/".
* <p>
* It replaces the text without showing the autocomplete popup.
* Bear in mind it won't work if you use a custom adapter not extending {@link ArrayAdapter}.
* <p>
*/
public static class ReplaceAutocompleteTextAction implements ViewAction {
private final String stringToBeSet;
public ReplaceAutocompleteTextAction(String value) {
checkNotNull(value);
this.stringToBeSet = value;
}
@SuppressWarnings("unchecked")
@Override
public Matcher<View> getConstraints() {
return allOf(isDisplayed(), isAssignableFrom(AutoCompleteTextView.class));
}
@Override
public void perform(UiController uiController, View view) {
AutoCompleteTextView autocomplete = (AutoCompleteTextView) view;
ArrayAdapter adapter = (ArrayAdapter) autocomplete.getAdapter();
autocomplete.setAdapter(null);
((EditText) view).setText(stringToBeSet);
autocomplete.setAdapter(adapter);
}
@Override
public String getDescription() {
return "replace text without showing autocomplete suggestions";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment