Search code examples
androidxmlsearchview

SearchView is not showing


I've tried a million ways to place the SearchView in my snippet. I read the documentation and tutorials all day long and nothing worked. I stopped at this:

search_menu.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/app_name"
          android:icon="@drawable/ic_baseline_search_24"
          app:showAsAction="collapseActionView|ifRoom"
          />
  </menu>

java code

public class Search_offer extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.activity_search_offer,container,false);
    }

    public void onStart(){
        super.onStart();
}

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();

        inflater.inflate(R.menu.search_menu, menu);
        MenuItem item = menu.findItem(R.id.search);
        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_IF_ROOM);

        SearchView searchView = (SearchView) item.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }

        });
    }

}

I can't figure out why it's not showing in any way. Help please


Solution

  • Could you run it and show compilation or run errors? I think, I don't get the problem fully.

    Here's some tips for menus:

    1. When you are starting you can use app:showAsAction="always"

    In that case small icon, which you choose should apesr in the app bar. So you can do it to chcech if image appears at all (to learn).

    1. Second of all - probably program have a problem to find a SearchView, because you forgot to add "app:actionVieClass". In that case your code should throw error during calling this line (SearchView) item.getActionVie().

    Checkout this video - maybe it will be helpfull: https://youtu.be/9OWmnYPX1uc