gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:52:06 29 4
gpt4 key购买 nike

我在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: Attempt to invoke virtual method 'void android.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference

最佳答案

在菜单布局中使用 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>

除此之外,您的重构可能没有正确完成。请尝试Refactor > Migrate to AndroidX 然后按DoRefactor

关于android - 迁移 android X androidx.appcompat.widget.SearchView 后获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416942/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com