概述
在Android开发中,当系统数据项比较多时,常常会在app添加搜索功能,方便用户能快速获得需要的数据。搜索栏对于我们并不陌生,在许多app都能见到它,比如豌豆荚
在某些情况下,我们希望我们的自动补全信息可以不只是纯文本,还可以像豌豆荚这样,能显示相应的图片和其他数据信息,因此Android给我们提供的AutoCompleteTextView往往就不够用,在大多情况下我们都需要自己去实现搜索框。
分析
根据上面这张图,简单分析一下自定义搜索框的结构与功能,有
1. 搜索界面大致由三部门组成,如图:输入框+(自动补全)提示框+结果列表。
2. 提示框的数据与输入框输入的文本是实时联动的,而结果列表只有在每次进行搜索操作时才会更新数据
3. 输入框的UI应是动态的,即UI随着输入的文本的改变而改变,如:在未输入文本时,清除按钮
应该是隐藏的;只有当框中有文本时才会显示。
4. 软键盘也应该是动态的,如完成搜索时应自动隐藏。
5. 选择提示框的选项会自动补全输入框,且自动进行搜索
6. (external)有热门搜索推荐/记录搜索记录的功能——热门搜索推荐列表只在刚要进行搜索的时候弹出,即未输入文本时,可供用户选择。
根据上面的分析,我们认为一个搜索框应该包含输入框和提示框两个部分。搜索框可以设置一个回调监听接口,当需要进行搜索操作时,调用监听者的search()方法,从而实现具体的搜索操作以及结果列表的数据联动。
演示Demo
注意:
1. 这里,博主图方便没有模拟太多数据,而且提示框和热搜列表也都只是使用String类型的数据,各位看官们可以根据自身需要去设置item_layout和相应的adapter。
2. 由于个人习惯,博主在这个demo中使用了通用适配器,所以生成和设置adapter的代码比较简略,看官们可以根据传统的ViewHolder模式打造自己的adapter。或者学习一下通用适配器的打造。可以参考这里(鸿神博客Again)学习一下通用适配器的打造,在我的源码里面也有对应的源码。
实现
好了,说了那么多,开始来看代码吧
先看SearchView的布局文件 search_layout.xml
android:background="#eee"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
android:background="#eb4f38"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content">
android:id="@+id/search_et_input"
android:layout_gravity="center_vertical"
android:layout_margin="10dp"
android:drawableLeft="@drawable/search_icon"
android:drawablePadding="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/search_edittext_shape"
android:textSize="16sp"
android:imeOptions="actionSearch"
android:inputType="text"
android:hint="请输入关键字"/>
android:visibility="gone"
android:layout_marginRight="20dp"
android:src="@drawable/iv_delete_bg"
android:id="@+id/search_iv_delete"
android:layout_gravity="right|center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
android:id="@+id/search_btn_back"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_gravity="center_vertical"
android:background="@drawable/btn_search_bg"
android:layout_width="@dimen/btn_width"
android:layout_height="@dimen/btn_height"
android:text=