Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SearchView using AppCompat

I implemented SearchView in Actionbar before using appcompat.v7 but when I want to use the SearchView with support library v7 it shows null exception

In style

<item android:id="@+id/action_search"
    android:title="@string/action_search"
    android:icon="@drawable/ic_action_search"
    app:showAsAction="always|collapseActionView"
    android:actionViewClass="android.support.v7.widget.SearchView" />

In Java Class:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setOnQueryTextListener(this);
    return super.onCreateOptionsMenu(menu);
}

My question is how to declare SearchView in onCreateOptionsMenu to be able to set query listener?

like image 961
A7madev Avatar asked Oct 25 '14 17:10

A7madev


People also ask

How do I customize SearchView?

just do your own search view, it is very simple. you then can include this layout in your activity layout file. This is a simple layout which includes a "search icon" followed by EditText, followed by "clear icon". The clear icon is shown after user types some text.

How do I use search view?

Android SearchView provides user interface to search query submitted over search provider. SearchView widget can be implemented over ToolBar/ActionBar or inside a layout. SearchView is by default collapsible and set to be iconified using setIconifiedByDefault(true) method of SearchView class.

What is Androidx Appcompat widget?

Allows dynamic tint of its background via the background tint methods in ViewCompat . AppCompatEditText. A EditText which supports compatible features on older versions of the platform, including: Allows dynamic tint of its background via the background tint methods in ViewCompat . AppCompatImageButton.


2 Answers

You should use the static methods in MenuItemCompat do deal with all AppCompat menu items. This was mentioned in this blog post as the last item under 'New Integration'. Just replace your SearchView declaration with the following.

SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));

Here's a link to the MenuItemCompat documentation.

Edit: I just assumed you are using the latest version of AppCompat with the support for the new Toolbar widget.

like image 69
ebarrenechea Avatar answered Oct 28 '22 06:10

ebarrenechea


If you change android:actionViewClass to app:actionViewClass your existing code will continue working.

like image 29
Espen Riskedal Avatar answered Oct 28 '22 07:10

Espen Riskedal