迁移android X后获取null androidx.appcompat.widget.SearchView

时间:2019-10-16 15:32:55

标签: android android-layout android-fragments

我已在xml中添加了android X

 public boolean onCreateOptionsMenu(final Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.notebook_menu, menu);
    MenuItem searchMenuItem = menu.findItem(R.id.notebook_search);      
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchView = (SearchView) searchMenuItem.getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false);    
    }

从菜单

  <menu xmlns:android="http://schemas.android.com/apk/res/android" >
        <item
        android:id="@+id/notebook_search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:icon="@drawable/tab_notebook_search"
        app:showAsAction="always|collapseActionView"
        android:title="@string/search"/>
        </menu>

错误

  

java.lang.NullPointerException:尝试调用虚拟方法'void   android.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)'   在空对象引用上

1 个答案:

答案 0 :(得分:1)

在菜单布局中使用app:actionViewClass代替android:actionViewClass。那就是问题所在。更改如下:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/notebook_search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:icon="@drawable/tab_notebook_search"
        app:showAsAction="always|collapseActionView"
        android:title="@string/search"/>
</menu>

此外,您的重构可能未正确完成。请尝试重构>迁移到AndroidX ,然后按 DoRefactor