Android搜尋功能的案例,本地儲存搜尋歷程記錄
同事負責開發的APP有一個搜尋功能,並且需要顯示搜尋的記錄,我閑暇之餘幫她開發了這個功能,現把該頁面抽取成一個demo分享給大家。
實現效果:
本案例實現起來很簡單,所以可以直接拿來嵌入項目中使用,涉及到的知識點:
- 資料庫的增刪改查操作
- ListView和ScrollView的嵌套衝突解決
- 監聽軟鍵盤迴車按鈕設定為搜尋按鈕
- 使用TextWatcher( )即時篩選
- 已搜尋的關鍵字再次搜尋不重複添加到資料庫
- 剛進入版面設定軟鍵盤不因為EditText而自動彈出
代碼
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(""); } }); // 搜尋方塊的鍵盤搜尋鍵點擊回調 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); // 按完搜尋鍵後將當前查詢的關鍵字儲存起來,如果該關鍵字已經存在就不執行儲存 boolean hasData = hasData(et_search.getText().toString().trim()); if (!hasData) { insertData(et_search.getText().toString().trim()); queryData(""); } // TODO 根據輸入的內容模糊查詢商品,並跳轉到另一個介面,由你自己去實現 Toast.makeText(MainActivity.this, "clicked!", Toast.LENGTH_SHORT).show(); } return false; } }); // 搜尋方塊的文本變化即時監聽 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("搜尋結果"); } String tempName = et_search.getText().toString(); // 根據tempName去模糊查詢資料庫中有沒有資料 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上面的文字,根據該關鍵字跳轉到另一個頁面查詢,由你自己去實現 } }); // 插入資料,便於測試,否則第一次進入沒有資料怎麼測試呀? Date date = new Date(); long time = date.getTime(); insertData("Leo" + time); // 第一次進入查詢所有的記錄 queryData(""); } /** * 插入資料 */ private void insertData(String tempName) { db = helper.getWritableDatabase(); db.execSQL("insert into records(name) values('" + tempName + "')"); db.close(); } /** * 模糊查詢資料 */ 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); // 建立adapter配接器物件 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); // 設定適配器 listView.setAdapter(adapter); adapter.notifyDataSetChanged(); } /** * 檢查資料庫中是否已經有該條記錄 */ private boolean hasData(String tempName) { Cursor cursor = helper.getReadableDatabase().rawQuery( "select id as _id,name from records where name =?", new String[]{tempName}); //判斷是否有下一個 return cursor.moveToNext(); } /** * 清空資料 */ 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); // 調整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
<code class=" hljs 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="fill_parent" android:layout_weight="264" android:background="@null" android:drawableleft="@drawable/search" android:drawablepadding="8dp" android:gravity="start|center_vertical" android:hint="輸入查詢的關鍵字" android:imeoptions="actionSearch" android:singleline="true" android:textcolor="@android:color/white" android:textsize="16sp"> </edittext></imageview></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> </textview></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> </textview></linearlayout> </scrollview></linearlayout></code>