1. 程式人生 > >簡單實現Android搜尋功能 顯示清除歷史搜尋記錄

簡單實現Android搜尋功能 顯示清除歷史搜尋記錄

本文主要為大家分享了Android實現搜尋功能,並且可以實時顯示搜尋的歷史記錄,根據輸入的內容去模糊查詢,供大家參考,介面圖如下。


本案例實現起來也非常的簡單,所以可以直接拿來嵌入專案中使用,主要涉及到的知識點:

1、資料庫的增刪改查操作

2、監聽軟鍵盤迴車按鈕設定為搜尋按鈕 

3、使用TextWatcher( )進行實時篩選 

4、已搜尋的關鍵字再次搜尋不會重複新增到資料庫 

既然是要儲存搜尋記錄,首先得建立資料庫表:
/**
 * 搜尋記錄幫助類
 * Created by 05 on 2016/7/27.
 */
public class RecordSQLiteOpenHelper extends SQLiteOpenHelper {

    private final static String DB_NAME = "temp.db";
    private final static int DB_VERSION = 1;

    public RecordSQLiteOpenHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sqlStr = "CREATE TABLE IF NOT EXISTS records (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);";
        db.execSQL(sqlStr);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

資料庫操作類 ,增刪改查都在裡面:
/**
 * 搜尋記錄操作類
 * Created by 05 on 2016/7/27.
 */
public class RecordsDao {
    RecordSQLiteOpenHelper recordHelper;

    SQLiteDatabase recordsDb;

    public RecordsDao(Context context) {
        recordHelper = new RecordSQLiteOpenHelper(context);
    }

    //新增搜尋記錄
    public void addRecords(String record) {

        if (!isHasRecord(record)) {
            recordsDb = recordHelper.getReadableDatabase();
            ContentValues values = new ContentValues();
            values.put("name", record);
            //新增
            recordsDb.insert("records", null, values);
            //關閉
            recordsDb.close();
        }
    }

    //判斷是否含有該搜尋記錄
    public boolean isHasRecord(String record) {
        boolean isHasRecord = false;
        recordsDb = recordHelper.getReadableDatabase();
        Cursor cursor = recordsDb.query("records", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            if (record.equals(cursor.getString(cursor.getColumnIndexOrThrow("name")))) {
                isHasRecord = true;
            }
        }
        //關閉資料庫
        recordsDb.close();
	cursor.close();
        return isHasRecord;
    }

    //獲取全部搜尋記錄
    public List<String> getRecordsList() {
        List<String> recordsList = new ArrayList<>();
        recordsDb = recordHelper.getReadableDatabase();
        Cursor cursor = recordsDb.query("records", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
            recordsList.add(name);
        }
        //關閉資料庫
        recordsDb.close();
	cursor.close();
        return recordsList;
    }

    //模糊查詢
    public List<String> querySimlarRecord(String record){
        String queryStr = "select * from records where name like '%" + record + "%' order by name ";
        List<String> similarRecords = new ArrayList<>();
        Cursor cursor= recordHelper.getReadableDatabase().rawQuery(queryStr,null);

        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
            similarRecords.add(name);
        }

	cursor.close();
        return similarRecords;
    }

    //清空搜尋記錄
    public void deleteAllRecords() {
        recordsDb = recordHelper.getWritableDatabase();
        recordsDb.execSQL("delete from records");

        recordsDb.close();
    }

}

資料庫類已經封裝好了,接下來就是介面程式碼:

<span style="color:#333333;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:background="@color/base_green"
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <LinearLayout
            android:layout_margin="10dp"
            android:background="@drawable/input_border_layout"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent">

            <ImageView
                android:padding="5dp"
                android:layout_gravity="center_vertical"
                android:layout_width="30dp"
                android:layout_height="match_parent"
                android:src="@mipmap/my_village_search"/>

            <EditText
                android:id="@+id/input_search_content_et"
                android:layout_margin="5dp"
                android:textSize="14sp"
                android:singleLine="true"
                android:imeOptions="actionSearch"
                android:layout_gravity="center_vertical"
                android:background="@drawable/input_no_border_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="請輸入你要搜尋的內容"/></span>
<!-- 以上的singleLine和imeOptions屬性程式碼是將彈出的軟鍵盤的回車鍵替換成搜尋鍵的關鍵,當然也可以換成傳送鍵 等等,可以去查一下該屬性 --></span>
        </LinearLayout>

        <TextView
            android:id="@+id/search_content_cancel_tv"
            android:padding="10dp"
            android:layout_gravity="center_vertical"
            android:gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:textSize="18sp"
            android:text="取消"
            android:textColor="@color/white"/>

    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:id="@+id/search_content_show_ll"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </LinearLayout>

    </RelativeLayout>

</LinearLayout></span>


因為是將搜尋的歷史資訊做成顯示隱藏的效果,所以單獨寫了一個歷史資訊的layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ListView
            android:id="@+id/search_records_lv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.1dp"
            android:background="@color/custom_gray"/>

        <TextView
            android:background="@color/white"
            android:id="@+id/clear_all_records_tv"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:textSize="16sp"
            android:gravity="center"
            android:textColor="@color/clear_red"
            android:text="清除歷史記錄"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.1dp"
            android:background="@color/custom_gray"/>

    </LinearLayout>

</LinearLayout>

既然用到了listview來顯示歷史搜尋資訊,就需要寫listview的item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:background="@color/white"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="40dp">

        <TextView
            android:id="@+id/search_content_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@mipmap/search_icon"
            android:drawablePadding="8dp"
            android:layout_margin="10dp"
            android:layout_gravity="center_vertical"
        />

    </LinearLayout>

</LinearLayout>

用到了listview,當然還需要介面卡,因為目前只有文字可以使用SimpleAdapter,為了以後能新增別的,我還是自定義了一個Adapter:
/**
 * Created by 05 on 2016/7/27.
 */
public class SearchRecordsAdapter extends BaseAdapter {

    private Context context;
    private List<String> searchRecordsList;
    private LayoutInflater inflater;

    public SearchRecordsAdapter(Context context, List<String> searchRecordsList) {
        this.context = context;
        this.searchRecordsList = searchRecordsList;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return searchRecordsList.size() == 0 ? 0 : searchRecordsList.size();
    }

    @Override
    public Object getItem(int position) {
        return searchRecordsList.size() == 0 ? null : searchRecordsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if(null == convertView){
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.saerch_records_list_item,null);
            viewHolder.recordTv = (TextView) convertView.findViewById(R.id.search_content_tv);

            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }

        String content = searchRecordsList.get(position);
        viewHolder.recordTv.setText(content);

        return convertView;
    }

    private class ViewHolder {
        TextView recordTv;
    }
}

最後就是介面程式碼了:
/**
 * 搜尋介面
 * Created by 05 on 2016/7/26.
 */
public class SearchContentActivity extends BaseActivity implements View.OnClickListener {
    private EditText searchContentEt;
    private SearchRecordsAdapter recordsAdapter;
    private View recordsHistoryView;
    private ListView recordsListLv;
    private TextView clearAllRecordsTv;
    private LinearLayout searchRecordsLl;

    private List<String> searchRecordsList;
    private List<String> tempList;
    private RecordsDao recordsDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_search_content);

        initView();
        initData();
        bindAdapter();
        initListener();
    }

    private void initView() {
        setHideHeader();
        initRecordsView();

        searchRecordsLl = (LinearLayout) findViewById(R.id.search_content_show_ll);
        searchContentEt = (EditText) findViewById(R.id.input_search_content_et);

        //新增搜尋view
        searchRecordsLl.addView(recordsHistoryView);

    }

    //初始化搜尋歷史記錄View
    private void initRecordsView() {
        recordsHistoryView = LayoutInflater.from(this).inflate(R.layout.search_records_list_layout, null);
        //顯示歷史記錄lv
        recordsListLv = (ListView) recordsHistoryView.findViewById(R.id.search_records_lv);
        //清除搜尋歷史記錄
        clearAllRecordsTv = (TextView) recordsHistoryView.findViewById(R.id.clear_all_records_tv);
    }


    private void initData() {
        recordsDao = new RecordsDao(this);
        searchRecordsList = new ArrayList<>();
        tempList = new ArrayList<>();
        tempList.addAll(recordsDao.getRecordsList());

        reversedList();
        //第一次進入判斷資料庫中是否有歷史記錄,沒有則不顯示
        checkRecordsSize();
    }


    private void bindAdapter() {
        recordsAdapter = new SearchRecordsAdapter(this, searchRecordsList);
        recordsListLv.setAdapter(recordsAdapter);
    }

    private void initListener() {
        clearAllRecordsTv.setOnClickListener(this);
        searchContentEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (searchContentEt.getText().toString().length() > 0) {

                        String record = searchContentEt.getText().toString();

                        //判斷資料庫中是否存在該記錄
                        if (!recordsDao.isHasRecord(record)) {
                            tempList.add(record);
                        }
                        //將搜尋記錄儲存至資料庫中
                        recordsDao.addRecords(record);
                        reversedList();
                        checkRecordsSize();
                        recordsAdapter.notifyDataSetChanged();

                        //根據關鍵詞去搜索
                        
                    } else {
                        ToastUtils.showToast(SearchContentActivity.this, "搜尋內容不能為空");
                    }
                }
                return false;
            }
        });

        //根據輸入的資訊去模糊搜尋
        searchContentEt.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) {
                String tempName = searchContentEt.getText().toString();
                tempList.clear();
                tempList.addAll(recordsDao.querySimlarRecord(tempName));
                reversedList();
                checkRecordsSize();
                recordsAdapter.notifyDataSetChanged();
            }
        });

        //歷史記錄點選事件
        recordsListLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //將獲取到的字串傳到搜尋結果介面

            }
        });
    }

    //當沒有匹配的搜尋資料的時候不顯示歷史記錄欄
    private void checkRecordsSize(){
        if(searchRecordsList.size() == 0){
            searchRecordsLl.setVisibility(View.GONE);
        }else{
            searchRecordsLl.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //清空所有歷史資料
            case R.id.clear_all_records_tv:
                tempList.clear();
                reversedList();
                recordsDao.deleteAllRecords();
                recordsAdapter.notifyDataSetChanged();
                searchRecordsLl.setVisibility(View.GONE);
                break;
        }
    }

    //顛倒list順序,使用者輸入的資訊會從上依次往下顯示
    private void reversedList(){
        searchRecordsList.clear();
        for(int i = tempList.size() - 1 ; i >= 0 ; i --){
            searchRecordsList.add(tempList.get(i));
        }
    }
}

以上就是實現搜尋記錄儲存,搜尋資訊模糊查詢的全部程式碼了,供大家參考,當然也給自己提供一個整理思路的鍛鍊。O(∩_∩)O~

相關推薦

簡單實現Android搜尋功能 顯示清除歷史搜尋記錄

本文主要為大家分享了Android實現搜尋功能,並且可以實時顯示搜尋的歷史記錄,根據輸入的內容去模糊查詢,供大家參考,介面圖如下。 本案例實現起來也非常的簡單,所以可以直接拿來嵌入專案中使用,主要涉及到的知識點: 1、資料庫的增刪改查操作 2、監聽軟鍵盤迴車按鈕設

安卓音、視頻播放功能簡單實現 --Android基礎

ket undle 顯示 perm err efault 繼續 bre mpat 1、音樂播放功能 關鍵代碼: MainActivity.java: package thonlon.example.cn.musicdemowithoutservice;import

PHP簡單實現分頁功能 (九步) 搜尋實現

//分頁步驟 //1 設定頁大小 //2 計算記錄總數 //3 計算頁總數 //4 接受當前頁碼?page=2 //5 過濾越界 //6 組裝sql語句 //7 傳送sql語句 //8 處理結果 //9 傳送超連結 //搜尋區域 $keyword=empty($_GET

Android簡單實現高德地圖顯示及定位

1、要實現高德地圖的定位,首先要下載高德地圖的SDK 下載地址:http://lbs.amap.com/api/android-location-sdk/download/ 然後在高德地圖官網上登入你註冊的賬號並且去控制檯

c語言簡單實現word count功能

判斷 ref 使用 href .cn nbu ext p s span c語言簡單實現word count功能 一:源碼參考 參考地址:https://home.cnblogs.com/u/sunbuqiao/ 二:閱讀

簡單實現qq登入功能

1.qq互聯下載sdk http://wiki.connect.qq.com/sdk 2.設定需要獲取的資訊 標題 配置完成後只保留API目錄下的檔案其他的可以刪除 程式碼 public function qqlogin(){

Ajax非同步表單簡單實現收索功能

非同步收索的作用簡單來說就是:在不更新整個網頁的情況下更新你想改變的網頁某個部分。   下面是實現: 1.準備工作     在mvc5 中要用Ajax,首先要新增jQuery的Ajax檔案。方法:右擊專案--管理NuGet程式包--查詢jQuery--找到關於Ajax的,然後

簡單實現Android視訊播放器倍速、清晰度切換、m3u8下載

簡單的前提是使用開源庫 在庫的基礎上新增相對應的功能, 以 JiaoZiVideoPlayer 為例 ,本身自帶的播放引擎是MediaPlayer,也就是Android自帶的播放器,有很多不完善的地方,倍速切換隻支援5.0以上,否則報 NoClassDefFoundError 錯誤

搜尋實現,常用搜索,歷史搜尋

1、實現功能 2、頁面佈局HTML 共三部分 (1)搜尋欄 input 框,右邊是一個a標籤,可以跳轉回前一頁面。之後寫元素用來放置歷史搜尋和常用搜索。 <form class="weui-search-bar__form" id="search-for

寫一個自己的Spring框架——簡單實現IoC容器功能

package cn.shu.IocFactory.impl; import org.jdom.input.SAXBuilder; import org.jdom.Document; import org.jdom.JDOMException; import org.jdom.Element; import

vue簡單實現記住密碼功能

原理是在提交表單的時候把使用者名稱和密碼的值存入cookie中然後再次進入頁面時讀取cookiehtml部分<div class="log_form">                <div class="log_form_biao">蚊子蚊子蚊子&

簡單實現Android頂部工具欄和底部工具欄

直接上圖,有圖有真相。 這兩個工具欄全是用佈局來實現的。 底部工具欄佈局程式碼: <?xml version="1.0" encoding="utf-8"?><RelativeLayout     ="http://schemas.androi

基於ssm下用jQuery簡單實現點贊功能

    自己寫專案的時候了用到了這個點贊與取消讚的功能,然後突然心血來潮,想在這裡寫篇部落格,也算是小小的總結一下,廢話不多說了,給大家上圖上碼才是重點。    下圖是知乎裡面的我的文章的截圖,現在就是要實現他的點贊功能。下圖是我自己寫的頁面jsp頁面點贊那一塊的程式碼:&l

Java Web中簡單實現自動登陸功能

Java 對自動登陸功能的簡單實現,僅用到了servlet和一個filter。第一次寫博文,如有不足的地方,敬請指正,謝謝。 登陸介面 <%@ page language="java" import="java.util.*" pageEncoding="UTF

簡單實現Android圖片三級快取機制

    使用者在使用我們的APP時,通常會重複瀏覽一些圖片,這時如果每一次瀏覽都需要通過網路獲取圖片,那麼將會非常流量。為了節省使用者流量,提高圖片載入效率,我們通常使用圖片三級快取策略,即通過網路、本地、記憶體三級快取圖片,來減少不必要的網路互動,避免浪費流量

簡單實現android炫酷註冊頁面動畫

最近比較閒,再加上以前懶惰的習慣,決定儘量保持幾天一篇部落格,這次簡單實現一下這個效果.其實主要是在網上看到了一篇部落格,裡面的效果比較炫,只是我覺得那個之前那個部落格的動畫有些地方的銜接沒有做好,並且沒有真正還原原設計,所以這裡重新寫了一下,簡單的實現.原部落

(工作小總結)Django REST Framework 效能優化,簡單實現預載入功能

緣由: Django 的 ORM 是惰性的每個使用者訪問網站時候,都要進行一次資料互動 在最初開發的時候,需要考慮到使用者量大的時候, 又由於 Django 的 ORM 是惰性的,它只取出當前查詢所需響應最小的資料。它不知道你是否有成百上千的相同或相似的

linux下遞迴刪除資料夾,簡單實現rm的功能

/*******************myrm.c 閫掑綊鐨勫垹闄や竴涓洰褰曘€?*鏉ㄥ環鍚?2009.4.8*淇敼錛?*******************/ #include<stdio.h>#include<stdlib.h>#includ

WebView詳解與簡單實現Android與H5互調

本篇文章已授權微信公眾號 guolin_blog (郭霖)獨家釋出 為什麼要學習Android與H5互調? 微信,QQ空間等大量軟體都內嵌了H5,不得不說是一種趨勢。Android與H5互調可以讓我們的實現混合開發,至於混合開發就是在一個App中內嵌

簡單實現京東訂單功能

提示      慎重複制 1  網路許可權 2  匯入依賴  compile 'com.android.support:recyclerview-v7:25.1.0' compile 'com.squareup.okhttp3:okhttp:3.4.1'