如何在android中处理Search View的后退按钮

前端之家收集整理的这篇文章主要介绍了如何在android中处理Search View的后退按钮前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(Menus.SEARCH));
searchView.setQueryHint(this.getString(R.string.search));
editSearch = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
editSearch.setHintTextColor(getResources().getColor(R.color.white));
searchView.setOnQueryTextListener(OnQuerySearchView);


private OnQueryTextListener OnQuerySearchView = new OnQueryTextListener() {

    @Override
    public boolean onQueryTextSubmit(String newText) {
        if (TextUtils.isEmpty(newText)) {
            listAllContact.clearTextFilter();
        } else {
            listAllContact.setFilterText(newText.toString());
        }
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        String text = editSearch.getText().toString()
                .toLowerCase(Locale.getDefault());
        adapter.filter(text);
        return true;
    }

};

解决方法

如果您使用android.support.v7.widget.SearchView作为菜单项:
<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"
        android:title=""
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

您可以使用以下方式处理后退按钮(用于展开状态):

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu,menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    searchItem.expandActionView();
    MenuItemCompat.setOnActionExpandListener(searchItem,new MenuItemCompat.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            // Write your code here
            return true;
        }
    });
}

猜你在找的Android相关文章