Android之debug---menu的getActionView()return null

时间:2020-12-23 15:06:23

MainActivity代码

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu); // Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView(); searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName())); return true;
}

main代码

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

错误问题:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference
at com.example.android.basiccontactables.MainActivity.onCreateOptionsMenu(MainActivity.java:)

错误解决:

将main代码中的android:actionViewClass="android.widget.Search"修改为app:actionViewClass="android.widget.Search"即可。

main修改之后如下:

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