我正在尝试在我的Android应用程序的工具栏中构建一个searchview,但是在onCreateoptionsMenu方法的第3行中得到了一个空指针异常。任何帮助将不胜感激,谢谢你。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager =(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
这是我的menu.xml -
<item
android:icon="@drawable/ic_search"
android:id="@+id/action_search"
android:orderInCategory="200"
android:title="Search"
app:showAsAction="ifRoom" />
答案 0 :(得分:0)
尝试更改此行:
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
答案 1 :(得分:0)
在菜单中设置SearchView类。
<item
android:icon="@drawable/ic_search"
android:id="@+id/action_search"
android:orderInCategory="200"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom" />
答案 2 :(得分:0)
您错过了app:actionViewClass="android.support.v7.widget.SearchView"
属性。
您需要导入android.support.v7.widget.SearchView;
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@drawable/search"
android:title="@string/Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView" />
</menu>
答案 3 :(得分:0)
您忘了在menu.xml中添加actionViewClass
将这些行添加到menu.xml
...
app:showAsAction="always|collapseActionView"
android:actionViewClass="android.support.v7.widget.SearchView" />
在Java代码中使用 -
查找SearchView
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
参考 - MenuItemCompat
答案 4 :(得分:0)
尝试使用此
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.menu_main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appcompat="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/tools">
<item
android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
app:showAsAction="never"/>
<item
android:id="@+id/menu_search"
android:title="@string/menu_search"
appcompat:actionViewClass="android.support.v7.widget.SearchView"
appcompat:showAsAction="always"/>