本文实例为大家分享了AndroID实现搜索功能,并且需要显示搜索的历史记录,供大家参考,具体内容如下
效果图:
本案例实现起来很简单,所以可以直接拿来嵌入项目中使用,涉及到的知识点:
- 数据库的增删改查 *** 作
- ListVIEw和ScrollVIEw的嵌套冲突解决
- 监听软键盘回车按钮设置为搜索按钮
- 使用TextWatcher( )实时筛选
- 已搜索的关键字再次搜索不重复添加到数据库
- 刚进入页面设置软键盘不因为EditText而自动d出
代码
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 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,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,60,60);// 第一0是距左边距离,第二0是距上边距离,60分别是长宽 et_search.setCompoundDrawables(drawable,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="输入查询的关键字" 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>
以上就是本文的全部内容,希望对大家的学习有所帮助。
总结以上是内存溢出为你收集整理的Android实现搜索功能并本地保存搜索历史记录全部内容,希望文章能够帮你解决Android实现搜索功能并本地保存搜索历史记录所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)