问题
The problem occurs when interacting with the SearchView or when the activity with the Searchview loads. When using setIconifiedByDefault(true)
the problem occurs after the activity loads when interacting with the SearchView, but when using setIconifiedByDefault(false)
the problem occurs when the activity loads.
The following error is output in LogCat:
java.lang.NullPointerException
at android.widget.SearchView.adjustDropDownSizeAndPosition(SearchView.java:1244)
Here is the code:
ExampleActivity.java
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.example, menu);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();
search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(true);
search.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// Perform search
return true;
}
});
}
return true;
}
menu/example.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/search"
android:title="Search"
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView" />
</menu>
xml/searchable.xml
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/search"
android:hint="@string/search" >
</searchable>
The "search" string used in searchable.xml is defined in values/strings.xml. Also the searchable.xml file is referenced correctly in the activity tag in AndroidManifest.xml:
<meta-data
android:name="android.app.default_searchable"
android:value="com.example.MainActivity" />
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
回答1:
This problem is caused by styles being applied to the EditText
in the action bar SearchView
.
You can fix this by removing any style you have applied to EditText
such as:
res/values/styles.xml
<item name="android:editTextStyle">@style/editor</item>
Then go to each EditText
view in your layout XML and apply the style directly:
<EditText style="@style/editor" />
来源:https://stackoverflow.com/questions/22295138/android-action-bar-searchview-nullpointerexception-adjustdropdownsizeandposition