运行结果:


涉及要点:

  • ListView EditText ScrollView实现搜索效果显示
  • 监听软键盘回车执行搜索
  • 使用TextWatcher( )实时筛选
  • 将搜索内容存储到SQLite中(可清空历史记录)
  • 监听EditText的焦点,获得焦点弹出软键盘同时显示搜索历史,失去焦点隐藏软件盘和ListView。

实现过程比较简单,都是常用的,这里就不讲解了。代码可直接复制使用。

实现过程:

MainActivity.java

public class MainActivity extends Activity {

 private EditText et_search;
 private TextView tv_tip;
 private MyListView listView;
 private TextView tv_clear;
 ScrollView scrollView;
 private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
 private SQLiteDatabase db;
 private BaseAdapter adapter;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 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("");
   }
   Toast.makeText(MainActivity.this, "点击软键盘搜索!", Toast.LENGTH_SHORT).show();
  }
  return false;
  }
 });

 et_search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
  @Override
  public void onFocusChange(View view, boolean b) {
  if (b) { //获得
   scrollView.setVisibility(View.VISIBLE);
  } else {//市区焦点
   scrollView.setVisibility(View.GONE);
  }
  }
 });

 // 搜索框的文本变化实时监听
 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();
  ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
   getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); //隐藏软键盘
  et_search.clearFocus();
  et_search.setText("");
  }
 });

 // 插入测试数据
 Date date = new Date();
 long time = date.getTime();
 insertData("LY"   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);
 scrollView = findViewById(R.id.showSearch);
 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);// 只放左边
 }
}

RecordSQLiteOpenHelper.java

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) {

 }
}

MyListView.java

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:focusable="true"
 android:focusableInTouchMode="true"
 android:orientation="vertical"
 tools:context=".MainActivity">

 <LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="50dp"
 android:background="#be9999"
 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" />

 </LinearLayout>

 <ScrollView
 android:id="@ id/showSearch"
 android:layout_width="wrap_content"
 android:layout_height="300dp"
 android:visibility="gone">

 <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" />

  <liyue.edu.cn.ncst.app.MyListView
   android:id="@ id/listView"
   android:layout_width="match_parent"
   android:layout_height="wrap_content" />
  </LinearLayout>

  <View
  android:layout_width="match_parent"
  android:layout_height="1dp"
  android:background="#EEEEEE" />

  <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" />
 </LinearLayout>

 </ScrollView>

</LinearLayout>

完整代码下载 demo

到此这篇关于android实现搜索功能并将搜索结果保存到SQLite中(实例代码)的文章就介绍到这了,更多相关android 搜索功能搜索结果保存sqlite内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

android实现搜索功能并将搜索结果保存到SQLite中(实例代码)的更多相关文章

  1. html5 canvas合成海报所遇问题及解决方案总结

    这篇文章主要介绍了html5 canvas合成海报所遇问题及解决方案总结,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Html5 video标签视频的最佳实践

    这篇文章主要介绍了Html5 video标签视频的最佳实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  3. HTML5在微信内置浏览器下右上角菜单的调整字体导致页面显示错乱的问题

    HTML5在微信内置浏览器下,在右上角菜单的调整字体导致页面显示错乱的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

  4. ios – containerURLForSecurityApplicationGroupIdentifier:在iPhone和Watch模拟器上给出不同的结果

    我使用默认的XCode模板创建了一个WatchKit应用程序.我向iOSTarget,WatchkitAppTarget和WatchkitAppExtensionTarget添加了应用程序组权利.(这是应用程序组名称:group.com.lombax.fiveminutes)然后,我尝试使用iOSApp和WatchKitExtension访问共享文件夹URL:延期:iOS应用:但是,测试NSURL

  5. PhoneGap / iOS上的SQLite数据库 – 超过5mb可能

    我误解了什么吗?Phonegap中的sqlitedbs真的有5mb的限制吗?我正在使用Phonegap1.2和iOS5.解决方法您可以使用带有phonegap插件的原生sqliteDB,您将没有任何限制.在iOS5.1中,Websql被认为是可以随时删除的临时数据…

  6. ios – 备份.sqlite(核心数据)

    我有一个基于核心数据的应用程序,它使用DropBox备份和恢复数据.我备份的方式非常简单.我复制用户的保管箱上的.sqlite文件.现在我的备份和恢复功能正常.问题出在.sqlite文件本身.看来.sqlite文件不完整.我在我的应用程序中输入了大约125个条目并进行了备份.备份出现在我的DropBox中但是当我使用.sqlite资源管理器工具查看内容时,我只看到第117个记录的记录.我尝试更新第

  7. ios – 多个NSPersistentStoreCoordinator实例可以连接到同一个底层SQLite持久性存储吗?

    我读过的关于在多个线程上使用CoreData的所有内容都讨论了使用共享单个NSPersistentStoreCoordinator的多个NSManagedobjectContext实例.这是理解的,我已经使它在一个应用程序中工作,该应用程序在主线程上使用CoreData来支持UI,并且具有可能需要一段时间才能运行的后台获取操作.问题是NSPersistentStoreCoordinator会对基础

  8. Ionic – Splash Screen适用于iOS,但不适用于Android

    我有一个离子应用程序,其中使用CLI命令离子资源生成的启动画面和图标iOS版本与正在渲染的启动画面完美配合,但在Android版本中,只有在加载应用程序时才会显示白屏.我检查了config.xml文件,所有路径看起来都是正确的,生成的图像出现在相应的文件夹中.(我使用了splash.psd模板来生成它们.我错过了什么?这是config.xml文件供参考,我觉得我在这里做错了–解决方法在config.xml中添加以下键:它对我有用!

  9. ios – 设置DataBase的加密密钥(Sybase Unwired Platform)

    目前,我可以通过执行以下操作为本地数据库设置加密密钥:因此,当我的用户成功登录时,我收到以下错误:我认为正在发生的是,虽然数据库已成功创建,但仍然是加密的.我该如何解密?解决方法实际上这很简单,我每次开始会话时都需要这样做:

  10. ios – 使用SQLite和CoreData进行批量插入

    我有一个使用sqlite作为持久性存储的CoreData模型.在对每条记录进行一些处理之后,我需要插入大量的行.有没有办法将这些命令发送到sqlite我需要加快处理时间,因为它需要几个小时才能完成.任何提示将不胜感激.谢谢解决方法将商店添加到商店协调员时,可以指定编译指示:(改编自PersistentStoreFeatures)我强烈建议您阅读“有效导入数据”.相关文档:NSSQLitePragm

随机推荐

  1. Flutter 网络请求框架封装详解

    这篇文章主要介绍了Flutter 网络请求框架封装详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Android单选按钮RadioButton的使用详解

    今天小编就为大家分享一篇关于Android单选按钮RadioButton的使用详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

  3. 解决android studio 打包发现generate signed apk 消失不见问题

    这篇文章主要介绍了解决android studio 打包发现generate signed apk 消失不见问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

  4. Android 实现自定义圆形listview功能的实例代码

    这篇文章主要介绍了Android 实现自定义圆形listview功能的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. 详解Android studio 动态fragment的用法

    这篇文章主要介绍了Android studio 动态fragment的用法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. Android用RecyclerView实现图标拖拽排序以及增删管理

    这篇文章主要介绍了Android用RecyclerView实现图标拖拽排序以及增删管理的方法,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下

  7. Android notifyDataSetChanged() 动态更新ListView案例详解

    这篇文章主要介绍了Android notifyDataSetChanged() 动态更新ListView案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

  8. Android自定义View实现弹幕效果

    这篇文章主要为大家详细介绍了Android自定义View实现弹幕效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  9. Android自定义View实现跟随手指移动

    这篇文章主要为大家详细介绍了Android自定义View实现跟随手指移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Android实现多点触摸操作

    这篇文章主要介绍了Android实现多点触摸操作,实现图片的放大、缩小和旋转等处理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部