1

I have a SearchView on my Toolbar. I works perfectly and I have no problem with it.

But the problem arises whenever I write some search term on the EditText of the SearchView and long-click on the text, the toolbar transforms into a contextual menu with paste, copy, etc options.

enter image description here

This also happened in other EditTexts of my app, but I solved it using

android:longClickable="false"

This entirely disables long-click event on the EditTexts and the context menu never appears. This is the behavior I want.

But how can I do the same for the SearchView? I tried to disable long-click on the SearchView but that doesn't work.

How can I reference the EditText of the SearchView and then disable the long-click event? Or is there any other better approach?

Aritra Roy
  • 15,355
  • 10
  • 73
  • 107

1 Answers1

2

This is how I solved it.

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

        SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
        searchView.setIconifiedByDefault(true);
        searchView.setQueryHint(getActivity().getString(R.string.search_files_hint));

        search = menu.findItem(R.id.search);

        MenuItemCompat.setOnActionExpandListener(search,
                new MenuItemCompat.OnActionExpandListener() {
                    @Override
                    public boolean onMenuItemActionCollapse(MenuItem item) {
                        return true; // Return true to collapse action view
                    }

                    @Override
                    public boolean onMenuItemActionExpand(MenuItem item) {

                        // Disabling long-click on the SearchView to remove the CAB glitch
                        TextView searchText = (TextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
                        if(searchText != null){
                            searchText.setLongClickable(false);
                        }

                        return true; // Return true to expand action view
                    }
                });

    }

The SearchView is not a simple View, rather a compound View consisting of a lot of Views.

On investigating further, I found that it has a SearchAutoComplete view which indirectly inherits from the EditText.

So, I just found a reference for it and if its not NULL then I setLongClickable to false.

But the trick here is to use it only when the SearchView is expanded, otherwise the SearchAutoComplete view is never inflated and is always null.

Aritra Roy
  • 15,355
  • 10
  • 73
  • 107