蜂窝3.2上的android searchview setOnActionExpandListener
问题内容:
我正在使用开发Android 3.2及更高版本的应用android- support-v4
。OnActionExpandListener
当操作栏中的SearchView展开时和折叠时,我需要实现“拦截”。我的Android
4.0及更高版本的代码还可以,但3.2版本没有。
menu.xml
<item android:id="@+id/menu_search"
android:title="@string/menu_search"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="collapseActionView|always"
android:actionViewClass="android.widget.SearchView" />
MyActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.reader, menu);
final MenuItem searchMI = menu.findItem(R.id.menu_search);
if(searchView == null) {
//searchView = (SearchView) searchMI.getActionView();
searchView = (SearchView) MenuItemCompat.getActionView(searchMI);
searchView.setOnQueryTextListener(this);
searchView.setOnSuggestionListener(this);
searchView.setOnCloseListener(new OnCloseListener() {
@Override
public boolean onClose() {
//some code
return false;
}
});
}
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
MenuItemCompat.setShowAsAction(searchMI, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
MenuItemCompat.setOnActionExpandListener(searchMI, new OnActionExpandListener() {
/* (non-Javadoc)
* @see android.support.v4.view.MenuItemCompat.OnActionExpandListener#onMenuItemActionExpand(android.view.MenuItem)
*/
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
Toast.makeText(getApplicationContext(), "onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
return true;
}
/* (non-Javadoc)
* @see android.support.v4.view.MenuItemCompat.OnActionExpandListener#onMenuItemActionCollapse(android.view.MenuItem)
*/
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
Toast.makeText(getApplicationContext(), "onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
return true;
}
});
} else {
searchMI.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
Toast.makeText(getApplicationContext(), "MenuItem#onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
Toast.makeText(getApplicationContext(), "MenuItem#onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
为什么对于Honeycomb,不调用侦听器的方法?
非常感谢。
问题答案:
您可能会错过“ MenuItemCompat.OnActionExpandListener”接口具有静态实现,而不是实例方法的事实(就像我一样)。
因此,如果您有一个实现的类,MenuItemCompat.OnActionExpandListener
则需要在该类中将其安装为侦听器,如下所示:
MenuItem menuItem = menu.findItem(R.id.search);
if (menuItem != null) {
MenuItemCompat.setOnActionExpandListener(menuItem,this);
MenuItemCompat.setActionView(menuItem, mSearchView);
}
相同的范例适用于setActionView …而不是invoke
menuItem.setActionView(this)
,您将menuItem作为第一个参数传递给静态版本,MenuItemCompat.setActionView
然后再跟随其他参数。