Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android搜索功能的案例,本地保存搜索歷史記錄

Android搜索功能的案例,本地保存搜索歷史記錄

編輯:關於android開發

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>

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved