最佳答案
我刚刚实现了 v7 AppCompat
支持库,但是在我测试的每个 Android 版本(4.2.2,2.3.4... .)中,MenuItemCompat.getActionView
总是返回 null
SearchView
显示在操作栏中,但是它不响应触摸操作,也不展开来显示它的 EditText
,就像一个简单的图标。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
if (searchView != null) {
SearchViewCompat.setOnQueryTextListener(searchView, mOnQueryTextListener);
searchView.setIconifiedByDefault(false);
Log.d(TAG,"SearchView not null");
} else
Log.d(TAG, "SearchView is null");
}
return super.onCreateOptionsMenu(menu);
}
Menu.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/action_search"
app:showAsAction="always|collapseActionView"
android:icon="@drawable/abc_ic_search"
android:title="@string/action_bar_search"
android:actionViewClass="android.support.v7.widget.SearchView"/>
<item android:id="@+id/action_refresh"
android:icon="@drawable/refresh"
android:title="@string/action_bar_refresh"
app:showAsAction="ifRoom"/>
</menu>