我正在使用所有AppCompat主题更新我的应用程序。在这里,我遇到了一个空指针:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
setupNewSearchView(searchItem, searchManager);
return true;
}
private void setupNewSearchView(final MenuItem searchItem,
SearchManager searchManager) {
final SearchView searchView = (SearchView) searchItem.getActionView();
// Null at line below
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// Everything else below edited out
}
以下是我的关键导入项:
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
当更新到 AppCompat
时,我是否正确地认为这行代码必须更改?
final SearchView searchView = (SearchView) searchItem.getActionView();
更新:
我将其更改为以下内容
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
同样的空结果...
更新 - 添加XML
<?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/menu_search"
app:actionViewClass="android.support.v7.widget.SearchView"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="always"
android:title="search" />
<item
</menu>
LogCat:
10-24 11:49:07.040: E/AndroidRuntime(4846): java.lang.NullPointerException
10-24 11:49:07.040: E/AndroidRuntime(4846): at com.---.---.MainFragmentActivity.setupNewSearchView(MainFragmentActivity.java:1300)
10-24 11:49:07.040: E/AndroidRuntime(4846): at com.---.---.MainFragmentActivity.onCreateOptionsMenu(MainFragmentActivity.java:1292)
10-24 11:49:07.040: E/AndroidRuntime(4846): at android.app.Activity.onCreatePanelMenu(Activity.java:2538)
10-24 11:49:07.040: E/AndroidRuntime(4846): at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:275)
10-24 11:49:07.040: E/AndroidRuntime(4846): at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:276)
10-24 11:49:07.040: E/AndroidRuntime(4846): at android.support.v7.app.ActionBarActivityDelegate$1.onCreatePanelMenu(ActionBarActivityDelegate.java:79)
10-24 11:49:07.040: E/AndroidRuntime(4846): at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:1056)
10-24 11:49:07.040: E/AndroidRuntime(4846): at android.support.v7.app.ActionBarActivityDelegateBase.doInvalidatePanelMenu(ActionBarActivityDelegateBase.java:1259)