Add Search View in Android 9.

Note:-

If  androidx.appcompat.R.id.search_close_btn is not Working then change that line to android.support.v7.appcompat.R.id.search_close_btn

@Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_sales, menu);
        MenuItem searchItem = menu.findItem(R.id.search);

        searchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem menuItem) {
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem menuItem) {
                return true;
            }
        });


        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return true;
            }

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

        searchView.setQueryHint("Search");
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        View closeButton = searchView.findViewById(androidx.appcompat.R.id.search_close_btn);
        closeButton.setOnClickListener(v -> {
            
            searchView.setQuery("", false);
            searchView.clearFocus();
        });


        return true;
    }

Comments

Popular posts from this blog

Android Studio 3.5 or above usb device not detected in Android Studio or Unable to detect adb version, exit value: 0xc0000135. ADB depends on the Windows Universal C Runtime, which is usually installed by default via Windows Update. You may need to manually fetch and install the runtime package here: https://support.microsoft.com/en-ca/help/2999226/update-for-universal-c-runtime-in-windows

Lint found fatal errors while assembling a release target.

ViewModelProviders.of(this) is deprecated what to use instead ViewModelProviders.of(this) OR if you don't want to use ViewmodelFactory OR ViewModelProviders error.