Android项目类似淘宝 电商 搜索功能,监听软键盘搜索事件,延迟自动搜索,以及时间排序的搜索历史记录的实现
Android项目类似淘宝 电商 搜索功能,监听软键盘搜索事件,延迟自动搜索,以及时间排序的搜索历史记录的实现
发布时间:2016-12-28 来源:查字典编辑
摘要:最近跳槽去新公司,接受的第一个任务是在一个电商模块的搜索功能以及搜索历史记录的实现。需求和淘宝等电商的功能大体差不多,最上面一个搜索框,下面...

最近跳槽去新公司,接受的第一个任务是在 一个电商模块的搜索功能以及搜索历史记录的实现。

需求和淘宝等电商的功能大体差不多,最上面一个搜索框,下面显示搜索历史记录。在EditText里输入要搜索的关键字后,按软键盘的搜索按键/延迟xxxxms后自动搜索。然后将搜索的内容展示给用户/提示用户没有搜到相关信息。

历史记录是按时间排序的,最新的在前面,输入以前搜索过的关键字,例如牛仔裤(本来是第二条),会更新这条记录的时间,下次再看,牛仔裤的排列就在第一位了。并且有清除历史记录的功能。

整理需求,大致需要做的工作如下:

功能部分:

一,点击EditText,弹出软键盘输入法,右下键为【搜索】字样。

二,监听软键盘输入法按下【搜索】事件。

三,在EditText输入内容后,1000ms内无修改则 自动搜索功能。

四,保存按时间排序的历史记录,

五,清除历史记录

六,点击历史记录条目,将内容填充至EditText并自动执行搜索功能。

UI示意图如下:

Android项目类似淘宝 电商 搜索功能,监听软键盘搜索事件,延迟自动搜索,以及时间排序的搜索历史记录的实现1

===============UI的实现==================

搜索Header头部:

整体是一个水平方向LinearLayout,依次放置ImageVIew(返回箭头),EditText(搜索框),TextView(取消)。

布局文件如下:

<LinearLayout android:layout_width="match_parent" android:layout_height="45dp" android:background="@color/black_14141f" android:gravity="center_vertical" android:orientation="horizontal" android:paddingBottom="6dp" android:paddingTop="6dp"> <ImageView android:id="@+id/iv_back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="14dp" android:paddingRight="14dp" android:src="@drawable/icon_back" /> <RelativeLayout android:id="@+id/rl_search_layout" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:background="@drawable/shape_search_bj" android:gravity="center" android:orientation="horizontal"> <!-- <ImageView android:layout_centerVertical="true" android:layout_alignParentLeft="true" android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@drawable/icon_black_search" />--> <EditText android:id="@+id/et_search" android:layout_width="match_parent" android:layout_height="30dp" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:layout_toLeftOf="@+id/close" android:layout_toRightOf="@+id/tv" android:background="@null" android:hint="输入商品名或者店铺名称" android:imeOptions="actionSearch" android:singleLine="true" android:textColor="@color/black3" android:textColorHint="@color/gray_aaaaaa" android:textSize="14sp" /> <!-- <ImageView android:layout_centerVertical="true" android:layout_alignParentRight="true" android:id="@+id/clear_search" android:background="@drawable/icon_dialog_close" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textColor="@color/white" android:textSize="18sp" />--> </RelativeLayout> <TextView android:id="@+id/tv_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="14dp" android:layout_marginRight="14dp" android:gravity="center_vertical" android:text="取消" android:textColor="@color/white" android:textSize="18sp" /> </LinearLayout>

从项目中直接拷出的,自行替换资源文件。

==================================

历史记录布局:

用一个垂直布局的LinearLayout 包裹 TextView(历史搜索四个字) +ListVIew(搜索记录)+ListView的footerview(清除历史记录)实现。

(淘宝的应该是一个LIstVIew即可,历史搜索字样用ListVIew的HeaderView实现。而我们公司产品设计的历史搜索字样下面的分割线长度和历史记录item分割线长度不一样,我就直接用TextView做了,大同小异)

代码如下:

<LinearLayout android:id="@+id/ll_search_history" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="14dp" android:layout_marginLeft="14dp" android:layout_marginTop="14dp" android:drawableLeft="@drawable/brand_search_history_icon" android:drawablePadding="10dp" android:text="历史记录" android:textColor="#333333" /> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/bg_dfdfdf" /> <ListView android:id="@+id/listView" android:divider="@null" android:layout_width="match_parent" android:layout_height="wrap_content"></ListView> </LinearLayout>

分割线一般都是用View设置background实现,省的UI切图。

================功能实现部分==================

一,点击EditText,弹出软键盘输入法,右下键为【搜索】字样。

只需要在EditText控件的xml里配置如下属性即可:

android:imeOptions="actionSearch"

=================================

二,监听软键盘输入法按下【搜索】事件。

为EditText控件,设置OnEditorActionListener事件,判断当actionId == EditorInfo.IME_ACTION_SEARCH时,则是按下了 搜索按钮。

代码如下,这里我们隐藏了软键盘,并执行搜索请求。

mEditTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { // 先隐藏键盘 ((InputMethodManager) mEditTextSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); //搜索具体逻辑 //搜索请求转交给函数去处理: //search(String.valueOf(mEditTextSearch.getText())); Toast.makeText(MainActivity.this,"按下了搜索按钮",Toast.LENGTH_SHORT).show(); return true; } return false; } });

==================================

三,在EditText输入内容后,1000ms内无修改则 自动搜索功能。

这里是监听EditText的TextChangedListener,在afterTextChanged(Editable s) 回调方法中,首先判断当前当前EditText里的字符串是否为null/空,如果是空的,则不搜索,显示历史记录,如果不为空,则用Handler.sendMessageDelayed方法 延迟500ms/1000ms 执行搜索功能。

这里有个情况就是,如果用户在1000ms内又输入了新内容,删改了字符 ,应该对新内容进行延迟1000ms搜索,或者删除字符后为空,则不该搜索了,即用户在1000ms内变动后,应该以最新的情况进行如上逻辑判断。所以这里在判断前加入了一条语句,在每次afterTextChanged()方法执行时,都先判断mHandler里是否有未处理的搜索请求,如果有,先remove掉这条请求Message。

代码如下:这里引入Handler,主要是为了实现延迟自动搜索,以及方便取消搜索请求。

mEditTextSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { //文字变动 , 有未发出的搜索请求,应取消 if(mHandler.hasMessages(MSG_SEARCH)){ mHandler.removeMessages(MSG_SEARCH); } //如果为空 直接显示搜索历史 if(TextUtils.isEmpty(s)){ //showHistory(); }else {//否则延迟500ms开始搜索 mHandler.sendEmptyMessageDelayed(MSG_SEARCH,500); //自动搜索功能 删除 } } }); } private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { //搜索请求 Toast.makeText(MainActivity.this,"搜索中。。。。",Toast.LENGTH_SHORT).show(); //search(String.valueOf(mEditTextSearch.getText())); } }; private static final int MSG_SEARCH = 1;

==================================

四,按时间排序的历史记录,

我在封装的搜索方法中,就做了两件事,一 向服务器发出 搜索 关键字 的 请求。 二,同步将关键字保存至SharedPrefrences (用SP简称)中,作为历史记录。

一略过,这里主要说二。

将关键字保存至SP中,是以key-value的形式,这里我将时间以yyyyMMddHHmmss形式作为key,(用于后续排序),将关键字作为value存入。

由于历史记录要有一个可以更新的感觉(最新的在前面,输入以前搜索过的关键字,例如牛仔裤(本来是第二条),会更新这条记录的时间,下次再看,牛仔裤的排列就在第一位了。),所以我在每次保存关键字之前,都先从SP中查询一下(返回SP中所有数据),遍历这个返回的map,是否有该value的记录,如果有,则删除,因为后面紧跟着会插入一条该value的记录,所以用这种 删除+插入的操作,实现了SP更新 update 的功能(原本的SP只有 增 删 方法)。

保存历史记录代码如下:

private SimpleDateFormat mFormat; mFormat = new SimpleDateFormat("yyyyMMddHHmmss"); /** * 将历史记录保存至sp中,key=当前时间(20160302133455,便于排序) ,value=关键字 * @param keyWords */ private void saveSearchHistory(String keyWords) { //保存之前要先查询sp中是否有该value的记录,有则删除.这样保证搜索历史记录不会有重复条目 Map<String, String> historys = (Map<String, String>) SearchHistoryUtils.getAll(getActivity()); for (Map.Entry<String, String> entry : historys.entrySet()) { if(keyWords.equals(entry.getValue())){ SearchHistoryUtils.remove(getActivity(),entry.getKey()); } } SearchHistoryUtils.put(getActivity(), "" + mFormat.format(new Date()), keyWords); }

查询历史记录

查询时,也是先返回SP中所有的数据,返回的是一个MAP集合。然后取出MAP集合中的keySet,由于key是按照指定数字格式插入的,所以将KEY排序。这里是升序排序。

首先计算一下keySet的集合长度 keyLeng,即历史记录有多少条,

然后和要显示的最大条数(HISTORY_MAX,这里我们产品定义的是5条)比较,

如果历史记录条数 > 要显示条数,则取为HISTORY_MAX,5条。 否则用历史记录的条数 keyLeng。

然后循环取出返回的Map集合中的,按照key升序排列的,后n条数据,加入集合中用于显示,这里判断一下,如果要显示的数据集合的size不等于0,说明有历史记录,则要显示footerview(清空历史记录),否则则不显示。

代码如下:

/** * 最多显示几条历史记录 */ private static final int HISTORY_MAX = 5; /** * 从SP查询搜索历史,并按时间显示 */ private void showSearchHistory() { Map<String, String> hisAll = (Map<String, String>) SearchHistoryUtils.getAll(getActivity()); //将key排序升序 Object[] keys = hisAll.keySet().toArray(); Arrays.sort(keys); int keyLeng = keys.length; //这里计算 如果历史记录条数是大于 可以显示的最大条数,则用最大条数做循环条件,防止历史记录条数-最大条数为负值,数组越界 int hisLeng = keyLeng > HISTORY_MAX ? HISTORY_MAX : keyLeng; for (int i = 1; i <= hisLeng; i++) { mResults.add(hisAll.get(keys[keyLeng - i])); } mAdapter.setDatas(mResults); //如果size不为0 显示footerview mFooterView.setVisibility(0!=mResults.size()?View.VISIBLE:View.GONE); }

================================

五,清除历史记录

该功能很简单,清空SP里的数据即可,不过要同步更新一下ListVIew,以及footerVIew的可见性。

/** * 清楚历史记录 */ private void clearsearchHistory() { SearchHistoryUtils.clear(this); //同时刷新历史记录显示页面 //mResults = new ArrayList<>(); //mAdapter.setDatas(mResults); //如果size不为0 显示footerview //mFooterView.setVisibility(0!=mResults.size()?View.VISIBLE:View.GONE); }

==================================

六,点击历史记录条目,将内容填充至EditText并自动执行搜索功能。

没啥好说的,为ListView设置点击监听,然后为EditText setText()设置内容,同步执行seach操作。略。

==================================

七优化:为了防止历史记录条数越来越多,我在这个Fragment的onDestroy()方法里,调用了删除多余历史记录的方法,将SP中的元素数量一直控制在 要显示的最大条数之内:

思路:如果map集合数量大于,要显示的MAX,则说明要删除多余条目。

然后和查询显示历史记录逻辑一样,先对KEY排序,删除,key值比较小的多余的那几条即可。

代码如下:

/** * 删除多余的历史记录 * 如果历史记录数量大于限定数量(10条),则按key升序排序,删除前几条 */ private void delMoreSearchHistory() { Map<String, String> hisAll = (Map<String, String>) SearchHistoryUtils.getAll(this); if (hisAll.size() > HISTORY_MAX) { //将key排序升序 Object[] keys = hisAll.keySet().toArray(); Arrays.sort(keys); // LENGTH = 12 , MAX = 10 , I = 1,0,count =2; for (int i = keys.length - HISTORY_MAX - 1; i > -1; i--) { SearchHistoryUtils.remove(this, (String) keys[i]); } } }

================================================

这是我来新公司做的第一个小功能,特此记录一下,

其实这个功能思路大体如上,只不过用SP会有一些东西要手动处理一下,所以有些可以说的。

如果用数据库保存历史记录,直接利用select 查询条件 排序时间, delete也利用条件删除,更加简单。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持查字典教程网。

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新安卓软件开发学习
热门安卓软件开发学习
编程开发子分类