Search code examples
androidsearchview

SearchView in Toolbar implemented by Activity


In the app I'm trying to do, I want to implement search, that will call a rest api.

As I asked long Time ago on how to do a SearchView it works ok --> How to use SearchView in Toolbar Android

But now I want to try something "different" (To learn a little bit more). But I'm doing something wrong.

What I'm trying to do is make the Activity implmement SearchView.OnQueryTextListener , so whay I have is:

    public class PMov extends AppCompatActivity implements SearchView.OnQueryTextListener {    
    ....
    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menu_main, menu);
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        Toast.makeText(this, "TextSubmit", Toast.LENGTH_SHORT).show();
        Logger.d("onQueryTextSubmit: " + query);
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        Toast.makeText(this, "TextChange", Toast.LENGTH_SHORT).show();
        Logger.d("onQueryTextChange: " + newText);
        return false;
    }
}

And the 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/action_search"
        android:title="@string/action_search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always"
        android:icon="@android:drawable/ic_menu_search"/>
</menu>

But for some reason (for sure I'm missing something) the methods are not triggered when I click and "write" something in the SearchBox.

What I'm missing? All the example I found are similar to my post I did long time ago.


Solution

  • Find the solution... facepalm for me!

    as @Markkeen pointend, I was missing tell to SearchView who is listening, it becomes fixed doing this:

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menu_main, menu);
            MenuItem searchItem = menu.findItem(R.id.action_search);
            SearchView actionSearchView = (SearchView) searchItem.getActionView();
            actionSearchView.setOnQueryTextListener(this);
        }
    

    And with this, the methods onQueryTextSubmit and onQueryTextChange are trigged.

    Thanks!