Toolbar 结合 SearchView实现搜索功能(具备历史记录)

96
Arestory
2017.03.17 23:45* 字数 159

效果(不动请戳大图)

toolbar.gif

ToolBar添加 menu

toolbar.inflateMenu(R.menu.toolbar_menu);

menu 文件

<menu>
<item
        android:id="@+id/action_search_kl"
        android:title="@string/action_search_knowledge"
        android:orderInCategory="80"
        app:actionViewClass="android.support.v7.widget.SearchView" 
        android:icon="@drawable/ic_search"
        app:showAsAction="always" />
    
</menu>

根据 itemId 找到该 item


MenuItem item=  toolbar.findViewById(R.id.action_search_kl);

通过 menuitem 获取里面的 view,进行各种样式更改

private void initSearchView(final MenuItem item){
  
//通过 item 获取 actionview
    final SearchView searchView = (SearchView) item.getActionView();
        searchView.setQueryHint("搜索知识库");    
    
    //改变默认的搜索图标
    ((ImageView)searchView.findViewById(R.id.search_button)).setImageResource(R.drawable.ic_search);
    
    //搜索监听
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
                public boolean onQueryTextSubmit(String query) {
                    //在输入法按下搜索或者回车时,会调用次方法,在这里可以作保存历史记录的操作,我这里用了 sharepreference保存
            
             SPUtils spUtils = new SPUtils("knowledgeHistory");
                        spUtils.put(query, query);
                        presenter.searchKnowledge(query);
            
            
        
                        return false;
                    }        @Override
                public boolean onQueryTextChange(String newText) {
//输入字符则回调此方法


//当输入字符为空时,重新设置 item

if(newText==null||newText.length()==0){
 
 //由于实现了历史数据的功能,在此重新设置此 item才能实时生效
     initSearchView(item); }

            return false;
                    }
            });    
     //根据id-search_src_text获取TextView    
 searchViewOfKnowledge = (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text);    
//改变输入文字的颜色
    searchViewOfKnowledge.setTextColor(ContextCompat.getColor(HomeTabActivity.this, R.color.colorAccent));
    try {
    
//取出历史数据,你可以利用其他方式
        final List<String> arr = new ArrayList<>();  
        
        SPUtils spUtils = new SPUtils("knowledgeHistory");
                Map<String, ?> map = spUtils.getAll();
        
                for (String key : map.keySet()) {
                    arr.add(map.get(key).toString());
                    }
        
        //显示历史数据列表
                searchViewOfKnowledge.setThreshold(0);

//历史数据列表的 adapter,必须继承 ArrayAdater 或实现 filterable接口
        HistoryAdapter adapter = new HistoryAdapter(HomeTabActivity.this, R.layout.item_history, arr,searchView);
        
       //设置 adapter
                searchViewOfKnowledge.setAdapter(adapter);
        
        //如果重写了 Adapter 的 getView 方法,可以不用实现 item 监听(实现了也没用),否则必须实现监听,不然会报错 
                searchViewOfKnowledge.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        
                    @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                            searchView.setQuery(arr.get(position), true);
                            }
                    });
            } catch (NullPointerException e) {
            e.printStackTrace();
            }
    
//searchview 的关闭监听
    searchView.setOnCloseListener(new SearchView.OnCloseListener() {        @Override        public boolean onClose() {
                    return false;
                    }
            });}


历史列表的 adapter,带删除功能

item 布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
        android:gravity="center_vertical"
        android:layout_width="match_parent"
        android:background="@drawable/touch_bg"
        android:padding="10dp"
        android:clickable="true"
        android:layout_height="wrap_content">
    <TextView
            android:id="@+id/titleTv"
                android:text="hahaha"
                android:layout_centerVertical="true"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
    <ImageButton
            android:background="@drawable/ic_close"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_alignParentRight="true"
                android:layout_gravity="right"
                android:id="@+id/imageButton" />
        </RelativeLayout>


adapter

构造方法必须带有布局ID,传入SearchView 是为了点击 item 之后可以在SearchView 直接显示点击的文字

public HistoryAdapter(Context context, int resourceId, List<String> titles,SearchView searchView) {
    super(context, resourceId, objects);
        this.context=context;
        this.titles=titles;
        this.resourceId=resourceId;
        this.searchView=searchView;
    }

省略 getItem,getCount,getItemId方法,主要看 getView 中删除按钮的点击方法


holder.imageButton.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View view) {
            SPUtils spUtils = new SPUtils("knowledgeHistory");
        
            //从数据中移除该项
            spUtils.remove(titles.get(i));
        
            //从数据中移除该项
                titles.remove(i);
        
        //进行刷新
                notifyDataSetChanged();    }});


必须重写 ArrayAdapter的getFilter()方法,如果不重写此方法,只会一直显示历史列表,则无法实现输入文字进行筛选的效果


//用于保存原始数据

private List<String> mOriginalValues;

@NonNull@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint,FilterResults results) {
                    titles = (List<String>) results.values; // 得到筛选后的列表结果
                        notifyDataSetChanged();  // 刷新数据        }


@Override
        protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults results = new FilterResults();  
                            List<String> filteredArrList = new ArrayList<String>();
            if (mOriginalValues == null) {
            
            //保存一份未筛选前的完整数据
                            mOriginalValues = new ArrayList<String>(titles);
                           }             if (constraint == null || constraint.length() == 0) {                //如果接收到的文字为空,则不作比较,直接返回未筛选前的完整数据
                                results.count = mOriginalValues.size();
                                 results.values = mOriginalValues;
                            } else {
                            //遍历原始数据,与接收到的文字作比较,得到筛选结果
                                constraint = constraint.toString().toLowerCase();
                                for (int i = 0; i < mOriginalValues.size(); i++) {
                                    String data = mOriginalValues.get(i);                    if(data.toLowerCase().startsWith(constraint.toString())) {
                                            filteredArrList.add(data);
                                            }
                                    }
                                //返回得到的筛选列表
                                results.count = filteredArrList.size();
                                results.values = filteredArrList;            }            return results;        }    };    return filter;} 

Android 笔记
Web note ad 1