MainActivity代码
1 @Override 2 public boolean onCreateOptionsMenu(Menu menu) { 3 // Inflate the menu; this adds items to the action bar if it is present. 4 getMenuInflater().inflate(R.menu.main, menu); 5 6 // Associate searchable configuration with the SearchView 7 SearchManager searchManager = 8 (SearchManager) getSystemService(Context.SEARCH_SERVICE); 9 SearchView searchView = 10 (SearchView) menu.findItem(R.id.search).getActionView(); 11 12 13 searchView.setSearchableInfo( 14 searchManager.getSearchableInfo(getComponentName())); 15 16 return true; 17 }
main代码
1 <menu xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:app="http://schemas.android.com/apk/res-auto"> 3 <item android:id="@+id/search" 4 android:title="@string/search_title" 5 android:icon="@drawable/ic_search_api_holo_light" 6 app:showAsAction="collapseActionView|ifRoom" 7 android:actionViewClass="android.widget.SearchView" /> 8 </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:76)
错误解决:
将main代码中的android:actionViewClass="android.widget.Search"修改为app:actionViewClass="android.widget.Search"即可。
main修改之后如下:
1 <menu xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:app="http://schemas.android.com/apk/res-auto"> 3 <item android:id="@+id/search" 4 android:title="@string/search_title" 5 android:icon="@drawable/ic_search_api_holo_light" 6 app:showAsAction="collapseActionView|ifRoom" 7 app:actionViewClass="android.widget.SearchView" /> 8 </menu>