Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 電商搜索功能實戰:軟鍵盤搜索、延遲自動搜索與按時間排序的歷史記錄

編輯:關於 Android 程式設計

到新公司接手的頭一個任務,是在一個電商模塊裡實現搜索功能與搜索歷史記錄。需求和淘寶這類電商大同小異:頂部一個搜索框,下方展示歷史記錄;用戶在 EditText 裡輸入關鍵字後,既可以點軟鍵盤的「搜索」鍵觸發,也能在停止輸入若干毫秒後自動搜索,隨後把結果呈現出來或提示「未找到相關信息」。歷史記錄按時間排序,最新的排在最前;若再次搜索以前搜過的關鍵字,該條記錄的時間會被刷新、躍居首位;同時還要支持一鍵清空歷史。

梳理下來,大致要做這幾件事:

功能部分:

一,點擊 EditText 彈出軟鍵盤,回車鍵顯示為「搜索」字樣;

二,監聽軟鍵盤按下「搜索」的事件;

三,輸入內容後,若 1000ms 內無改動則自動搜索;

四,保存按時間排序的歷史記錄;

五,清除歷史記錄;

六,點擊歷史記錄條目,把內容回填到 EditText 並自動執行搜索。

UI 示意圖如下:

=============== 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 搞定,「歷史搜索」字樣作為 HeaderView;這裡因為設計稿要求標題下的分割線長度與記錄項的分割線不一致,就單獨用了 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 設置背景色來實現,省得讓 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; } }); 

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

三,輸入內容後 1000ms 內無改動則自動搜索。

這裡監聽 EditText 的 TextChangedListener,在 afterTextChanged 回調中先判斷內容是否為空:若為空則不搜索、直接展示歷史記錄;若不為空,則用 Handler.sendMessageDelayed 延遲觸發搜索。

需要特別處理一個情況:用戶可能在延遲窗口內又改了內容——那麼應當以最新內容重新計時;若改成空,則不該再搜索。因此每次 afterTextChanged 執行時,都要先檢查 Handler 裡是否有尚未發出的搜索請求,有的話先 remove 掉,再重新排隊。引入 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; 

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

四,按時間排序的歷史記錄。

我封裝的搜索方法主要做兩件事:一是向服務器發起搜索請求(這裡略過),二是把關鍵字同步保存到 SharedPreferences(下文簡稱 SP)作為歷史記錄。

存到 SP 是以 key-value 形式:把時間以 yyyyMMddHHmmss 格式作為 key(便於排序),關鍵字作為 value。由於歷史記錄要有「更新」的效果(搜過的老關鍵字會刷新時間、排到最前),我在每次保存前先查一遍 SP 裡所有數據,遍歷這個 map,若已存在相同 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),取出 keySet 後對 key 排序(升序)。先算出 keySet 的長度 keyLeng,即歷史記錄總條數;再與要展示的最大條數 HISTORY_MAX(這裡定義為 5 條)比較,取二者中較小者作為循環上限,防止數組越界;然後按 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); } 

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

六,點擊歷史記錄條目,回填內容並自動搜索。

給 ListView 設置點擊監聽,然後為 EditText setText() 填入內容,同步執行搜索即可,這裡不再展開。

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

七,優化:防止歷史記錄不斷膨脹。

我在 Fragment 的 onDestroy() 裡調用了刪除多餘記錄的方法,把 SP 中的元素數量始終控制在展示上限之內。思路和查詢顯示一致:若 map 數量超過 MAX,就對 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 會有不少東西需要手工處理,所以還是有值得說的地方。如果改用數據庫保存歷史記錄,直接利用 SQL 的排序查詢與條件刪除會更加省心。

以上就是本文的全部內容,希望對你的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved