Reputation: 6328
I have a SearchView in ActionBar.
I'd like to validate the text input by the user before submitting it to SearchManager.
What I mean is, if a user entered text less than 3 characters, then a Toast will pop up instead going to another activity that shows the search results.
Here is how I implement the SearchView:
In MainActivity
:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
Log.d(TAG, "submit= "+s);
if (s.length() < 4) Toast.makeText(getApplicationContext(), "More than 3 letter pl0x", Toast.LENGTH_LONG).show();
return true;
}
@Override
public boolean onQueryTextChange(String s) {
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
I just wanna make sure the user input is more than 3 characters. Is there a possible way to do this?
Upvotes: 1
Views: 1163
Reputation: 329
From the docs: "The listener can override the standard behavior by returning true to indicate that it has handled the submit request. Otherwise return false to let the SearchView handle the submission by launching any associated intent."
if (s.length() < 4) {
Toast.makeText(getApplicationContext(), "More than 3 letter pl0x", Toast.LENGTH_LONG).show();
return true;
} else {
return false;
}
Upvotes: 3
Reputation: 6081
there is a library from zasadnyy for this.
Click here https://github.com/zasadnyy/z-validations
I downloaded that library and added the class "HasMinimumLength". With that, you can check whether the length of the text is longer than the provided minimum character length.
Please take care, that you need to copy the strings from strings.xml
into your own strings and that you have to switch the imports. Meaning, in the validation classes instead of
import ua.org.zasadnyy.zvalidations.R
you should use import your.package.name.R
Upvotes: 1