运行结果:

涉及要点:

  • 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内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。