Material SearchView implementation error

喜你入骨 提交于 2019-12-06 04:23:41

Do you have added the following code on your manifest :

<activity
    android:name=".ActivityWhereYouWantYourSearch">
    ...
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>

    <meta-data android:name="android.app.searchable"
        android:resource="@xml/searchable"/>
</activity>

And this on your res/xml folder (named searchable.xml) :

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="@string/search_hint"
    android:label="@string/app_name"
    android:searchSettingsDescription="@string/search_description" />

I will also put a check on your onCreateOptionsMenu, like this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);

    MenuItem searchItem = menu.findItem(R.id.search_ad);
    if (searchItem != null) {
        SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) searchItem.getActionView();
        // Assumes current activity is the searchable activity
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
    }
    return true;
}

BTW, I don't use android:enabled and android:visible, but it's up to you to decide.

I'm not familiar with this kind of SearchView but from the error I would guess that it can't get the ComponentName of the Activity. What I would try now is to put a this before getComponentName() --> this.getComponentName() to make sure where it should get the ComponentName.

Just a guess, so please don't hate me if that's wrong ^^

You have to return true from onCreateOptionsMenu in order the inflation to take place. Therefore you get a NPE when trying to access menu before the return statement.

So remove those four lines of code to the appropriate method onPrepareOptionsMenu

I guess the issue with your code is that you are using the latest version of support library but using the old style to access the "SearchView", that's why it's returning null. Use this line of code to access your searchview through "MenuItemCompat":

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

Check this blog for more details:

https://chris.banes.me/2014/10/17/appcompat-v21/

Instead of

return true;

add this line

return super.onCreateOptionsMenu(menu);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!