0
I implemented a Searchview and put in a Toast to see if it was working as soon as I typed something in the search. Toast is not displayed, no error appears in Logcat. The search is in an Actionbar. When I click on the search icon, it expands to be able to type but once and hit "enter" / "confirm" Toast does not appear.
This is the part where I’m calling Search
public void pesquisar(MenuItem item){
searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(MainActivity.this, "ola", Toast.LENGTH_SHORT).show();
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sair:
this.finish();
case R.id.sobre:
return true;
case R.id.cadastrar:
Intent telaCadastro = new Intent(MainActivity.this, CadastroMaterias.class);
startActivity(telaCadastro);
case R.id.pesquisar:
pesquisar(item);
default:
return super.onOptionsItemSelected(item);
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item android:id="@+id/sobre"
android:title="Sobre"
android:orderInCategory="100"
app:showAsAction="never"/>
<item android:id="@+id/sair"
android:title="Sair"
android:orderInCategory="150"
app:showAsAction="never"/>
<item android:id="@+id/cadastrar"
android:title="Adicionar Materia"
android:orderInCategory="100"
android:icon="@drawable/ic_action_add"
app:showAsAction="ifRoom"/>
<item android:id="@+id/pesquisar"
android:title="Pesquisar"
android:orderInCategory="150"
android:icon="@drawable/ic_search"
app:showAsAction="always"
app:actionViewClass="android.widget.SearchView"/>
<item android:id="@+id/excluir"
android:title="Excluir todos os registros"
android:orderInCategory="200"
android:icon="@drawable/ic_delete"
app:showAsAction="ifRoom"/>
</menu>
You are calling the setOnQueryTextListener within the search function, but did you remember to call this function search() in your onCreate method so that the System is actually set in searchView? Or at some other time is it calling the search()? Try to put the Istener right in onCreate and see what happens, it doesn’t have all its code there but it can be this ;)
– leofontes
Got here, in XML, in the field item search switched to
app:actionViewClass="android.support.v7.widget.SearchView"/>
and also put areturn true
in methodpublic boolean onOptionsItemSelected(MenuItem item)
of the class where the search icon is.– Flávio