Android搜索功能

来源:互联网 发布:短网址生成源码 编辑:程序博客网 时间:2024/06/05 07:15

项目中的一个页面需要实现搜索查询功能,并且需求要在EditText下面显示历史查询记录和清除查询记录。网上逛了一圈,然后看到一篇不错的帖子,原创:http://blog.csdn.net/LeoLeoHan/article/details/50688283?locationNum=4&fps=1#comments
先设置软键盘右下角显示搜索,xml中设置俩个属性即可:

android:imeOptions="actionSearch"android:singleLine="true"

然后设置软键盘搜索监听:

search.setOnKeyListener(new View.OnKeyListener() {            @Override            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);                    Toast.makeText(MainActivity.this,"搜索",Toast.LENGTH_SHORT).show();                }                return false;            }        });

完整代码如下:
xml代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="50dp"        android:orientation="horizontal"        android:background="#cccccc">        <ImageView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center_vertical"            android:padding="10dp"            android:src="@drawable/back" />        <EditText            android:id="@+id/et_search"            android:layout_width="260dp"            android:layout_height="match_parent"            android:background="@null"            android:drawablePadding="8dp"            android:gravity="start|center_vertical"            android:hint="输入查询的关键字"            android:imeOptions="actionSearch"            android:singleLine="true"            android:textColor="@android:color/white"/>        <TextView            android:id="@+id/check"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="查询"            android:textSize="16sp"/>    </LinearLayout>    <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="wrap_content"                android:padding="10dp"                android:text="搜索历史" />            <View                android:layout_width="match_parent"                android:layout_height="1dp"                android:background="#EEEEEE"/>            <ListView                android:id="@+id/listView"                android:layout_width="match_parent"                android:layout_height="wrap_content"/>        </LinearLayout>        <TextView            android:id="@+id/clear_history"            android:layout_width="match_parent"            android:layout_height="40dp"            android:background="#EEEEEE"            android:gravity="center"            android:text="清除搜索历史" />    </LinearLayout></LinearLayout>

RecordSQLiteOpenHelper:

package com.example.lenovo.demo;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代码:

package com.example.lenovo.demo;import android.app.Activity;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.os.Handler;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.ListView;import android.widget.SimpleCursorAdapter;import android.widget.TextView;public class MainActivity extends Activity {    private EditText et_search;    private ListView listView;    private TextView clear_history;    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();        clear_history.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);                    //判断关键字是否已经保存,如果已经保存,就不需要再保存了                    checkRecord();                    //这里执行逻辑,跳转到另一个页面                }                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) {                final String tempName = et_search.getText().toString();                // 500ms后再根据tempName去模糊查询数据库中有没有数据,防止用户频繁改变输入的内容                new Handler().postDelayed(new Runnable() {                    @Override                    public void run() {                        queryData(tempName);                    }                },500);            }        });        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);                //这里根据选中的item执行逻辑,跳转到另一个页面            }        });        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 = 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);        listView = (ListView) findViewById(R.id.listView);        clear_history = (TextView) findViewById(R.id.clear_history);        findViewById(R.id.check).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                checkRecord();                //这里执行逻辑,跳转到另一个页面            }        });    }    public void checkRecord(){        boolean hasData = hasData(et_search.getText().toString().trim());        if (!hasData) {            insertData(et_search.getText().toString().trim());            queryData("");        }    }}
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 专升本学校有课怎么办 跨境额度超了怎么办 微商代购被骗了怎么办 减肥到了瓶颈期该怎么办 大润发超市把一件商品打两件怎么办 小红书上买到假货怎么办 主动退市股票钱怎么办 老板卷款逃跑财务怎么办 房开延迟交房怎么办 房开逾期交房怎么办 买了保险想退保怎么办 辐射避难所探索废土死了怎么办 大门上边的齿轮滑丝怎么办 国通石油储油卡怎么办 买大棚房受骗了怎么办 朋友做安利天天来我门面怎么办 安利优惠顾客卡怎么办 苹果手机天气温度不显示怎么办? 安利净水器坏了怎么办 安利净水器滤芯盖搭配坏怎么办 安利会员卡过期了怎么办 婴儿吃了润唇膏怎么办? 用错沐浴露洗头怎么办 雅蜜润肤沐浴露怎么办 自煮小火锅水放少了怎么办 安利皇后锅发黑怎么办 宝宝灌肠后不拉屎怎么办 吃蛋白质粉肚子长胖了怎么办 安利产品过期了怎么办 拼多多拼不到人怎么办 被海南大宗骗了怎么办 手机被游戏扣钱怎么办 做酵素剩下的水果怎么办 喝了酵素胃疼怎么办 海科融通不到账怎么办 美团外卖没生意怎么办 淘宝联盟领券销售怎么办 微信返利被骗了怎么办 众筹失败后资金怎么办 健身房不给退卡怎么办 婆婆陷入民间传销组织怎么办