Implementing search on mobile devices is always tricky. You need to consider design and especially user experience aspects.
No Submit Button
The tricky question we had to ask ourselves while implementing design and functionality: how to create a smooth search experience without a submit button?
Actually, there are some search implementations without a submit button. They’re used for features like auto-completion with a limited result set. We wanted to provide a search, where the user types his keywords, waits for the response of an API request to get results which then get displayed.
Solve the Problem: Delay EditTexts’s ChangedTextEvent
During auto-complete, you expect the results to get filtered with every key stroke. In contrast you want a search get triggered once you finished typing. In case the user didn’t finish typing his keywords, we’d execute a search request with every key typed.
To avoid that many requests and optimize search experience, you can use a TextWatcher
for the search field (EditText
). The TextWatcher
requires you to implement three methods:
beforeTextChanged
: perform operations before the text in EditText changesafterTextChanged
: perform operations after the text in EditText changesonTextChanged
: perform operations while the text in EditText changes
The following Java code example illustrates the use of mentioned methods and variables.
private EditText searchText;
private TextView resultText;
private Timer timer;
private TextWatcher searchTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
// user typed: start the timer
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// do your actual work here
}
}, 600); // 600ms delay before the timer executes the „run“ method from TimerTask
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// nothing to do here
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// user is typing: reset already started timer (if existing)
if (timer != null) {
timer.cancel();
}
}
};
This snippet just shows you the exemplary use case to solve the problem on how to guess when the user finished typing and wants to start the search without having a submit button. We use a delay of 600 milliseconds to start the search. If the user types another letter into the search field, we reset the timer and wait another 600 ms.
Video Preview
To get an impression of what we’re talking about, here is a video showing exemplary functionality of the search mechanism.
Example Code on GitHub
You can find the complete code for this example in the android-tutorials-delay-changedtextevent repository on GitHub.
We love to hear about your solutions if you implemented the same functionality with other methods. Please let us know about your solution and get in touch via the comments below or tweet us @futurestud_io.