Android實(shí)現(xiàn)搜索功能并本地保存搜索歷史記錄
本文實(shí)例為大家分享了Android實(shí)現(xiàn)搜索功能,并且需要顯示搜索的歷史記錄,供大家參考,具體內(nèi)容如下
效果圖:

本案例實(shí)現(xiàn)起來很簡單,所以可以直接拿來嵌入項(xiàng)目中使用,涉及到的知識(shí)點(diǎn):
- 數(shù)據(jù)庫的增刪改查操作
- ListView和ScrollView的嵌套沖突解決
- 監(jiān)聽軟鍵盤回車按鈕設(shè)置為搜索按鈕
- 使用TextWatcher( )實(shí)時(shí)篩選
- 已搜索的關(guān)鍵字再次搜索不重復(fù)添加到數(shù)據(jù)庫
- 剛進(jìn)入頁面設(shè)置軟鍵盤不因?yàn)镋ditText而自動(dòng)彈出
代碼
RecordSQLiteOpenHelper.java
package com.cwvs.microlife;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class RecordSQLiteOpenHelper extends SQLiteOpenHelper {
private static String name = "temp.db";
private static Integer version = 1;
public RecordSQLiteOpenHelper(Context context) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table records(id integer primary key autoincrement,name varchar(200))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
MainActivity.java
package com.cwvs.microlife;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_search;
private TextView tv_tip;
private MyListView listView;
private TextView tv_clear;
private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);;
private SQLiteDatabase db;
private BaseAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// 初始化控件
initView();
// 清空搜索歷史
tv_clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteData();
queryData("");
}
});
// 搜索框的鍵盤搜索鍵點(diǎn)擊回調(diào)
et_search.setOnKeyListener(new View.OnKeyListener() {// 輸入完后按鍵盤上的搜索鍵
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回車鍵功能
// 先隱藏鍵盤
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// 按完搜索鍵后將當(dāng)前查詢的關(guān)鍵字保存起來,如果該關(guān)鍵字已經(jīng)存在就不執(zhí)行保存
boolean hasData = hasData(et_search.getText().toString().trim());
if (!hasData) {
insertData(et_search.getText().toString().trim());
queryData("");
}
// TODO 根據(jù)輸入的內(nèi)容模糊查詢商品,并跳轉(zhuǎn)到另一個(gè)界面,由你自己去實(shí)現(xiàn)
Toast.makeText(MainActivity.this, "clicked!", Toast.LENGTH_SHORT).show();
}
return false;
}
});
// 搜索框的文本變化實(shí)時(shí)監(jiān)聽
et_search.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 (s.toString().trim().length() == 0) {
tv_tip.setText("搜索歷史");
} else {
tv_tip.setText("搜索結(jié)果");
}
String tempName = et_search.getText().toString();
// 根據(jù)tempName去模糊查詢數(shù)據(jù)庫中有沒有數(shù)據(jù)
queryData(tempName);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView textView = (TextView) view.findViewById(android.R.id.text1);
String name = textView.getText().toString();
et_search.setText(name);
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
// TODO 獲取到item上面的文字,根據(jù)該關(guān)鍵字跳轉(zhuǎn)到另一個(gè)頁面查詢,由你自己去實(shí)現(xiàn)
}
});
// 插入數(shù)據(jù),便于測試,否則第一次進(jìn)入沒有數(shù)據(jù)怎么測試呀?
Date date = new Date();
long time = date.getTime();
insertData("Leo" + time);
// 第一次進(jìn)入查詢所有的歷史記錄
queryData("");
}
/**
* 插入數(shù)據(jù)
*/
private void insertData(String tempName) {
db = helper.getWritableDatabase();
db.execSQL("insert into records(name) values('" + tempName + "')");
db.close();
}
/**
* 模糊查詢數(shù)據(jù)
*/
private void queryData(String tempName) {
Cursor cursor = helper.getReadableDatabase().rawQuery(
"select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
// 創(chuàng)建adapter適配器對(duì)象
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[] { "name" },
new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// 設(shè)置適配器
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
/**
* 檢查數(shù)據(jù)庫中是否已經(jīng)有該條記錄
*/
private boolean hasData(String tempName) {
Cursor cursor = helper.getReadableDatabase().rawQuery(
"select id as _id,name from records where name =?", new String[]{tempName});
//判斷是否有下一個(gè)
return cursor.moveToNext();
}
/**
* 清空數(shù)據(jù)
*/
private void deleteData() {
db = helper.getWritableDatabase();
db.execSQL("delete from records");
db.close();
}
private void initView() {
et_search = (EditText) findViewById(R.id.et_search);
tv_tip = (TextView) findViewById(R.id.tv_tip);
listView = (com.cwvs.microlife.MyListView) findViewById(R.id.listView);
tv_clear = (TextView) findViewById(R.id.tv_clear);
// 調(diào)整EditText左邊的搜索按鈕的大小
Drawable drawable = getResources().getDrawable(R.drawable.search);
drawable.setBounds(0, 0, 60, 60);// 第一0是距左邊距離,第二0是距上邊距離,60分別是長寬
et_search.setCompoundDrawables(drawable, null, null, null);// 只放左邊
}
}
MyListView.java
package com.cwvs.microlife;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class MyListView extends ListView {
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="#E54141"
android:orientation="horizontal"
android:paddingRight="16dp">
<ImageView
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center_vertical"
android:padding="10dp"
android:src="@drawable/back" />
<EditText
android:id="@+id/et_search"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@null"
android:drawableLeft="@drawable/search"
android:drawablePadding="8dp"
android:gravity="start|center_vertical"
android:hint="輸入查詢的關(guān)鍵字"
android:imeOptions="actionSearch"
android:singleLine="true"
android:textColor="@android:color/white"
android:textSize="16sp" />
</LinearLayout>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="20dp"
>
<TextView
android:id="@+id/tv_tip"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="left|center_vertical"
android:text="搜索歷史" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#EEEEEE"></View>
<com.cwvs.microlife.MyListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"></com.cwvs.microlife.MyListView>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#EEEEEE"></View>
<TextView
android:id="@+id/tv_clear"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#F6F6F6"
android:gravity="center"
android:text="清除搜索歷史" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginBottom="20dp"
android:background="#EEEEEE"></View>
</LinearLayout>
</ScrollView>
</LinearLayout>
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
- Android Studio搜索功能(查找功能)及快捷鍵圖文詳解
- Android自定義View實(shí)現(xiàn)搜索框(SearchView)功能
- Android仿簡書動(dòng)態(tài)searchview搜索欄效果
- Android百度地圖實(shí)現(xiàn)搜索和定位及自定義圖標(biāo)繪制并點(diǎn)擊時(shí)彈出泡泡
- Android搜索框SearchView屬性和用法詳解
- Android SearchView搜索框組件的使用方法
- Android遍歷所有文件夾和子目錄搜索文件
- Android搜索框組件SearchView的基本使用方法
- Android ListView用EditText實(shí)現(xiàn)搜索功能效果
- Android實(shí)現(xiàn)簡單動(dòng)態(tài)搜索功能
相關(guān)文章
Android使用TextView實(shí)現(xiàn)無下劃線超鏈接的方法
這篇文章主要介紹了Android使用TextView實(shí)現(xiàn)無下劃線超鏈接的方法,結(jié)合實(shí)例形式分析了Android中TextView超鏈接去除下劃線的相關(guān)實(shí)現(xiàn)技巧與注意事項(xiàng),需要的朋友可以參考下2016-08-08
Android使用MediaPlayer和TextureView實(shí)現(xiàn)視頻無縫切換
這篇文章主要為大家詳細(xì)介紹了Android使用MediaPlayer和TextureView實(shí)現(xiàn)視頻無縫切換,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10
Android基礎(chǔ)之使用Fragment控制切換多個(gè)頁面
Android官方已經(jīng)提供了Fragment的各種使用的Demo例子,在我們SDK下面的API Demo里面就包含了Fragment的各種使用例子,需要看Demo的朋友,直接看API Demo那個(gè)程序就可以了,不用到處去找。里面分開不同功能,實(shí)現(xiàn)了不同的類2013-07-07
android 實(shí)現(xiàn)控件左右或上下抖動(dòng)教程
這篇文章主要介紹了android 實(shí)現(xiàn)控件左右或上下抖動(dòng)教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Android Studio 安裝配置方法完整教程【小白秒懂】
這篇文章主要介紹了Android Studio 安裝配置方法完整教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2020-03-03
解決android有的手機(jī)拍照后上傳圖片被旋轉(zhuǎn)的問題
這篇文章主要介紹了解決android有的手機(jī)拍照后上傳圖片被旋轉(zhuǎn)的問題的相關(guān)資料,需要的朋友可以參考下2016-09-09
Android編程實(shí)現(xiàn)對(duì)文件夾里文件排序的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)對(duì)文件夾里文件排序的方法,涉及Android文件操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-01-01
android中ProgressDialog與ProgressBar的使用詳解
本篇文章是對(duì)android中ProgressDialog與ProgressBar的使用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
21天學(xué)習(xí)android開發(fā)教程之SurfaceView與多線程的混搭
21天學(xué)習(xí)android開發(fā)教程之SurfaceView與多線程的混搭,感興趣的小伙伴們可以參考一下2016-02-02

