Android項(xiàng)目類似淘寶 電商 搜索功能,監(jiān)聽軟鍵盤搜索事件,延遲自動(dòng)搜索,以及時(shí)間排序的搜索歷史記錄的實(shí)現(xiàn)
最近跳槽去新公司,接受的第一個(gè)任務(wù)是在 一個(gè)電商模塊的搜索功能以及搜索歷史記錄的實(shí)現(xiàn)。
需求和淘寶等電商的功能大體差不多,最上面一個(gè)搜索框,下面顯示搜索歷史記錄。在EditText里輸入要搜索的關(guān)鍵字后,按軟鍵盤的搜索按鍵/延遲xxxxms后自動(dòng)搜索。然后將搜索的內(nèi)容展示給用戶/提示用戶沒有搜到相關(guān)信息。
歷史記錄是按時(shí)間排序的,最新的在前面,輸入以前搜索過的關(guān)鍵字,例如牛仔褲(本來是第二條),會(huì)更新這條記錄的時(shí)間,下次再看,牛仔褲的排列就在第一位了。并且有清除歷史記錄的功能。
整理需求,大致需要做的工作如下:
功能部分:
一,點(diǎn)擊EditText,彈出軟鍵盤輸入法,右下鍵為【搜索】字樣。
二,監(jiān)聽軟鍵盤輸入法按下【搜索】事件。
三,在EditText輸入內(nèi)容后,1000ms內(nèi)無修改則 自動(dòng)搜索功能。
四,保存按時(shí)間排序的歷史記錄,
五,清除歷史記錄
六,點(diǎn)擊歷史記錄條目,將內(nèi)容填充至EditText并自動(dòng)執(zhí)行搜索功能。
UI示意圖如下:

===============UI的實(shí)現(xiàn)==================
搜索Header頭部:
整體是一個(gè)水平方向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>
從項(xiàng)目中直接拷出的,自行替換資源文件。
==================================
歷史記錄布局:
用一個(gè)垂直布局的LinearLayout 包裹 TextView(歷史搜索四個(gè)字) +ListVIew(搜索記錄)+ListView的footerview(清除歷史記錄)實(shí)現(xiàn)。
(淘寶的應(yīng)該是一個(gè)LIstVIew即可,歷史搜索字樣用ListVIew的HeaderView實(shí)現(xiàn)。而我們公司產(chǎn)品設(shè)計(jì)的歷史搜索字樣下面的分割線長度和歷史記錄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設(shè)置background實(shí)現(xiàn),省的UI切圖。
================功能實(shí)現(xiàn)部分==================
一,點(diǎn)擊EditText,彈出軟鍵盤輸入法,右下鍵為【搜索】字樣。
只需要在EditText控件的xml里配置如下屬性即可:
android:imeOptions="actionSearch"
=================================
二,監(jiān)聽軟鍵盤輸入法按下【搜索】事件。
為EditText控件,設(shè)置OnEditorActionListener事件,判斷當(dāng)actionId == EditorInfo.IME_ACTION_SEARCH時(shí),則是按下了 搜索按鈕。
代碼如下,這里我們隱藏了軟鍵盤,并執(zhí)行搜索請求。
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);
//搜索具體邏輯
//搜索請求轉(zhuǎn)交給函數(shù)去處理:
//search(String.valueOf(mEditTextSearch.getText()));
Toast.makeText(MainActivity.this,"按下了搜索按鈕",Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
==================================
三,在EditText輸入內(nèi)容后,1000ms內(nèi)無修改則 自動(dòng)搜索功能。
這里是監(jiān)聽EditText的TextChangedListener,在afterTextChanged(Editable s) 回調(diào)方法中,首先判斷當(dāng)前當(dāng)前EditText里的字符串是否為null/空,如果是空的,則不搜索,顯示歷史記錄,如果不為空,則用Handler.sendMessageDelayed方法 延遲500ms/1000ms 執(zhí)行搜索功能。
這里有個(gè)情況就是,如果用戶在1000ms內(nèi)又輸入了新內(nèi)容,刪改了字符 ,應(yīng)該對新內(nèi)容進(jìn)行延遲1000ms搜索,或者刪除字符后為空,則不該搜索了,即用戶在1000ms內(nèi)變動(dòng)后,應(yīng)該以最新的情況進(jìn)行如上邏輯判斷。所以這里在判斷前加入了一條語句,在每次afterTextChanged()方法執(zhí)行時(shí),都先判斷mHandler里是否有未處理的搜索請求,如果有,先remove掉這條請求Message。
代碼如下:這里引入Handler,主要是為了實(shí)現(xiàn)延遲自動(dòng)搜索,以及方便取消搜索請求。
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) {
//文字變動(dòng) , 有未發(fā)出的搜索請求,應(yīng)取消
if(mHandler.hasMessages(MSG_SEARCH)){
mHandler.removeMessages(MSG_SEARCH);
}
//如果為空 直接顯示搜索歷史
if(TextUtils.isEmpty(s)){
//showHistory();
}else {//否則延遲500ms開始搜索
mHandler.sendEmptyMessageDelayed(MSG_SEARCH,500); //自動(dòng)搜索功能 刪除
}
}
});
}
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;
==================================
四,按時(shí)間排序的歷史記錄,
我在封裝的搜索方法中,就做了兩件事,一 向服務(wù)器發(fā)出 搜索 關(guān)鍵字 的 請求。 二,同步將關(guān)鍵字保存至SharedPrefrences (用SP簡稱)中,作為歷史記錄。
一略過,這里主要說二。
將關(guān)鍵字保存至SP中,是以key-value的形式,這里我將時(shí)間以yyyyMMddHHmmss形式作為key,(用于后續(xù)排序),將關(guān)鍵字作為value存入。
由于歷史記錄要有一個(gè)可以更新的感覺(最新的在前面,輸入以前搜索過的關(guān)鍵字,例如牛仔褲(本來是第二條),會(huì)更新這條記錄的時(shí)間,下次再看,牛仔褲的排列就在第一位了。),所以我在每次保存關(guān)鍵字之前,都先從SP中查詢一下(返回SP中所有數(shù)據(jù)),遍歷這個(gè)返回的map,是否有該value的記錄,如果有,則刪除,因?yàn)楹竺婢o跟著會(huì)插入一條該value的記錄,所以用這種 刪除+插入的操作,實(shí)現(xiàn)了SP更新 update 的功能(原本的SP只有 增 刪 方法)。
保存歷史記錄代碼如下:
private SimpleDateFormat mFormat;
mFormat = new SimpleDateFormat("yyyyMMddHHmmss");
/**
* 將歷史記錄保存至sp中,key=當(dāng)前時(shí)間(20160302133455,便于排序) ,value=關(guān)鍵字
* @param keyWords
*/
private void saveSearchHistory(String keyWords) {
//保存之前要先查詢sp中是否有該value的記錄,有則刪除.這樣保證搜索歷史記錄不會(huì)有重復(fù)條目
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);
}
查詢歷史記錄
查詢時(shí),也是先返回SP中所有的數(shù)據(jù),返回的是一個(gè)MAP集合。然后取出MAP集合中的keySet,由于key是按照指定數(shù)字格式插入的,所以將KEY排序。這里是升序排序。
首先計(jì)算一下keySet的集合長度 keyLeng,即歷史記錄有多少條,
然后和要顯示的最大條數(shù)(HISTORY_MAX,這里我們產(chǎn)品定義的是5條)比較,
如果歷史記錄條數(shù) > 要顯示條數(shù),則取為HISTORY_MAX,5條。 否則用歷史記錄的條數(shù) keyLeng。
然后循環(huán)取出返回的Map集合中的,按照key升序排列的,后n條數(shù)據(jù),加入集合中用于顯示,這里判斷一下,如果要顯示的數(shù)據(jù)集合的size不等于0,說明有歷史記錄,則要顯示footerview(清空歷史記錄),否則則不顯示。
代碼如下:
/**
* 最多顯示幾條歷史記錄
*/
private static final int HISTORY_MAX = 5;
/**
* 從SP查詢搜索歷史,并按時(shí)間顯示
*/
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;
//這里計(jì)算 如果歷史記錄條數(shù)是大于 可以顯示的最大條數(shù),則用最大條數(shù)做循環(huán)條件,防止歷史記錄條數(shù)-最大條數(shù)為負(fù)值,數(shù)組越界
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里的數(shù)據(jù)即可,不過要同步更新一下ListVIew,以及footerVIew的可見性。
/**
* 清楚歷史記錄
*/
private void clearsearchHistory() {
SearchHistoryUtils.clear(this);
//同時(shí)刷新歷史記錄顯示頁面
//mResults = new ArrayList<>();
//mAdapter.setDatas(mResults);
//如果size不為0 顯示footerview
//mFooterView.setVisibility(0!=mResults.size()?View.VISIBLE:View.GONE);
}
==================================
六,點(diǎn)擊歷史記錄條目,將內(nèi)容填充至EditText并自動(dòng)執(zhí)行搜索功能。
沒啥好說的,為ListView設(shè)置點(diǎn)擊監(jiān)聽,然后為EditText setText()設(shè)置內(nèi)容,同步執(zhí)行seach操作。略。
==================================
七優(yōu)化:為了防止歷史記錄條數(shù)越來越多,我在這個(gè)Fragment的onDestroy()方法里,調(diào)用了刪除多余歷史記錄的方法,將SP中的元素?cái)?shù)量一直控制在 要顯示的最大條數(shù)之內(nèi):
思路:如果map集合數(shù)量大于,要顯示的MAX,則說明要?jiǎng)h除多余條目。
然后和查詢顯示歷史記錄邏輯一樣,先對KEY排序,刪除,key值比較小的多余的那幾條即可。
代碼如下:
/**
* 刪除多余的歷史記錄
* 如果歷史記錄數(shù)量大于限定數(shù)量(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]);
}
}
}
================================================
這是我來新公司做的第一個(gè)小功能,特此記錄一下,
其實(shí)這個(gè)功能思路大體如上,只不過用SP會(huì)有一些東西要手動(dòng)處理一下,所以有些可以說的。
如果用數(shù)據(jù)庫保存歷史記錄,直接利用select 查詢條件 排序時(shí)間, delete也利用條件刪除,更加簡單。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android自定義流式布局實(shí)現(xiàn)淘寶搜索記錄
- Android本地實(shí)現(xiàn)搜索歷史記錄
- Android實(shí)現(xiàn)搜索保存歷史記錄功能
- Android流式布局實(shí)現(xiàn)歷史搜索記錄功能
- Android實(shí)現(xiàn)搜索功能并本地保存搜索歷史記錄
- Android實(shí)現(xiàn)簡易計(jì)步器功能隔天步數(shù)清零查看歷史運(yùn)動(dòng)紀(jì)錄
- android中AutoCompleteTextView的簡單用法(實(shí)現(xiàn)搜索歷史)
- Android中使用 AutoCompleteTextView 實(shí)現(xiàn)手機(jī)號格式化附帶清空歷史的操作
- Android實(shí)現(xiàn)搜索歷史功能
- Android實(shí)現(xiàn)歷史搜索記錄
相關(guān)文章
詳解ListView中多種item的實(shí)現(xiàn)方式
這篇文章主要給大家介紹了關(guān)于ListView中多種item的實(shí)現(xiàn)方式,文中通過示例代碼介紹的很詳細(xì),有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-12-12
android 使用okhttp可能引發(fā)OOM的一個(gè)點(diǎn)
這篇文章主要介紹了android 使用okhttp可能引發(fā)OOM的一個(gè)點(diǎn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
Android開發(fā)實(shí)現(xiàn)調(diào)節(jié)屏幕亮度功能
這篇文章主要介紹了Android開發(fā)實(shí)現(xiàn)調(diào)節(jié)屏幕亮度功能,涉及Android權(quán)限控制及屏幕亮度相關(guān)屬性操作技巧,需要的朋友可以參考下2018-03-03
Android仿微信朋友圈點(diǎn)擊評論自動(dòng)定位到相關(guān)行功能
這篇文章主要介紹了android仿微信朋友圈點(diǎn)擊評論自動(dòng)定位到相關(guān)行功能的實(shí)現(xiàn),本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-05-05
Android實(shí)現(xiàn)可播放GIF動(dòng)畫的ImageView
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)可播放GIF動(dòng)畫的ImageView,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09
Android Studio+MAT實(shí)戰(zhàn)內(nèi)存泄漏
這篇文章主要介紹了Android Studio+MAT實(shí)戰(zhàn)內(nèi)存泄漏的相關(guān)技術(shù)內(nèi)容,并在需要注意的地方做了提示,需要參考學(xué)習(xí)下吧。2017-12-12
android BottomSheetDialog新控件解析實(shí)現(xiàn)知乎評論列表效果(實(shí)例代碼)
BottomSheetDialog是一個(gè)自定義的從底部滑入的對話框,這篇文章主要介紹了android BottomSheetDialog新控件解析實(shí)現(xiàn)知乎評論列表效果,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04
Android仿UC底部菜單欄實(shí)現(xiàn)原理與代碼
最近剛看完ViewPager,開始我打算用自定義的imgBtn,但是發(fā)現(xiàn)放在pager選項(xiàng)卡中不好排版,所以最好選了GridView,接下來介紹底部菜單欄實(shí)現(xiàn)2013-01-01
Android實(shí)現(xiàn)根據(jù)評分添加星級條
這篇文章主要介紹了Android實(shí)現(xiàn)根據(jù)評分添加星級條,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10

