简单实现Android搜索功能 显示清除历史搜索记录

本文主要为大家分享了Android实现搜索功能,并且可以实时显示搜索的历史记录,根据输入的内容去模糊查询,供大家参考,界面图如下。


本案例实现起来也非常的简单,所以可以直接拿来嵌入项目中使用,主要涉及到的知识点:

1、数据库的增删改查操作

2、监听软键盘回车按钮设置为搜索按钮 

3、使用TextWatcher( )进行实时筛选 

4、已搜索的关键字再次搜索不会重复添加到数据库 

既然是要保存搜索记录,首先得建立数据库表:

[java] view plain copy
  1. /** 
  2.  * 搜索记录帮助类 
  3.  * Created by 05 on 2016/7/27. 
  4.  */  
  5. public class RecordSQLiteOpenHelper extends SQLiteOpenHelper {  
  6.   
  7.     private final static String DB_NAME = "temp.db";  
  8.     private final static int DB_VERSION = 1;  
  9.   
  10.     public RecordSQLiteOpenHelper(Context context) {  
  11.         super(context, DB_NAME, null, DB_VERSION);  
  12.     }  
  13.   
  14.     @Override  
  15.     public void onCreate(SQLiteDatabase db) {  
  16.         String sqlStr = "CREATE TABLE IF NOT EXISTS records (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);";  
  17.         db.execSQL(sqlStr);  
  18.     }  
  19.   
  20.     @Override  
  21.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  22.   
  23.     }  
  24. }  

数据库操作类 ,增删改查都在里面:

[html] view plain copy
  1. /**  
  2.  * 搜索记录操作类  
  3.  * Created by 05 on 2016/7/27.  
  4.  */  
  5. public class RecordsDao {  
  6.     RecordSQLiteOpenHelper recordHelper;  
  7.   
  8.     SQLiteDatabase recordsDb;  
  9.   
  10.     public RecordsDao(Context context) {  
  11.         recordHelper = new RecordSQLiteOpenHelper(context);  
  12.     }  
  13.   
  14.     //添加搜索记录  
  15.     public void addRecords(String record) {  
  16.   
  17.         if (!isHasRecord(record)) {  
  18.             recordsDb = recordHelper.getReadableDatabase();  
  19.             ContentValues values = new ContentValues();  
  20.             values.put("name", record);  
  21.             //添加  
  22.             recordsDb.insert("records", null, values);  
  23.             //关闭  
  24.             recordsDb.close();  
  25.         }  
  26.     }  
  27.   
  28.     //判断是否含有该搜索记录  
  29.     public boolean isHasRecord(String record) {  
  30.         boolean isHasRecord = false;  
  31.         recordsDb = recordHelper.getReadableDatabase();  
  32.         Cursor cursor = recordsDb.query("records", null, null, null, null, null, null);  
  33.         while (cursor.moveToNext()) {  
  34.             if (record.equals(cursor.getString(cursor.getColumnIndexOrThrow("name")))) {  
  35.                 isHasRecord = true;  
  36.             }  
  37.         }  
  38.         //关闭数据库  
  39.         recordsDb.close();  
  40.     cursor.close();  
  41.         return isHasRecord;  
  42.     }  
  43.   
  44.     //获取全部搜索记录  
  45.     public List<String> getRecordsList() {  
  46.         List<String> recordsList = new ArrayList<>();  
  47.         recordsDb = recordHelper.getReadableDatabase();  
  48.         Cursor cursor = recordsDb.query("records", null, null, null, null, null, null);  
  49.         while (cursor.moveToNext()) {  
  50.             String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));  
  51.             recordsList.add(name);  
  52.         }  
  53.         //关闭数据库  
  54.         recordsDb.close();  
  55.     cursor.close();  
  56.         return recordsList;  
  57.     }  
  58.   
  59.     //模糊查询  
  60.     public List<String> querySimlarRecord(String record){  
  61.         String queryStr = "select * from records where name like '%" + record + "%' order by name ";  
  62.         List<String> similarRecords = new ArrayList<>();  
  63.         Cursor cursorrecordHelper.getReadableDatabase().rawQuery(queryStr,null);  
  64.   
  65.         while (cursor.moveToNext()) {  
  66.             String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));  
  67.             similarRecords.add(name);  
  68.         }  
  69.   
  70.     cursor.close();  
  71.         return similarRecords;  
  72.     }  
  73.   
  74.     //清空搜索记录  
  75.     public void deleteAllRecords() {  
  76.         recordsDb = recordHelper.getWritableDatabase();  
  77.         recordsDb.execSQL("delete from records");  
  78.   
  79.         recordsDb.close();  
  80.     }  
  81.   
  82. }  



数据库类已经封装好了,接下来就是界面代码:

[html] view plain copy
  1. <span style="color:#333333;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:orientation="vertical" android:layout_width="match_parent"  
  3.     android:layout_height="match_parent">  
  4.   
  5.     <LinearLayout  
  6.         android:background="@color/base_green"  
  7.         android:layout_width="match_parent"  
  8.         android:layout_height="50dp">  
  9.   
  10.         <LinearLayout  
  11.             android:layout_margin="10dp"  
  12.             android:background="@drawable/input_border_layout"  
  13.             android:layout_weight="1"  
  14.             android:layout_width="0dp"  
  15.             android:layout_height="match_parent">  
  16.   
  17.             <ImageView  
  18.                 android:padding="5dp"  
  19.                 android:layout_gravity="center_vertical"  
  20.                 android:layout_width="30dp"  
  21.                 android:layout_height="match_parent"  
  22.                 android:src="@mipmap/my_village_search"/>  
  23.   
  24.             <EditText  
  25.                 android:id="@+id/input_search_content_et"  
  26.                 android:layout_margin="5dp"  
  27.                 android:textSize="14sp"  
  28.                 android:singleLine="true"  
  29.                 android:imeOptions="actionSearch"  
  30.                 android:layout_gravity="center_vertical"  
  31.                 android:background="@drawable/input_no_border_layout"  
  32.                 android:layout_width="match_parent"  
  33.                 android:layout_height="wrap_content"  
  34.                 android:hint="请输入你要搜索的内容"/></span>  
  35. <!-- 以上的singleLine和imeOptions属性代码是将弹出的软键盘的回车键替换成搜索键的关键,当然也可以换成发送键 等等,可以去查一下该属性 --></span>  
  36.         </LinearLayout>  
  37.   
  38.         <TextView  
  39.             android:id="@+id/search_content_cancel_tv"  
  40.             android:padding="10dp"  
  41.             android:layout_gravity="center_vertical"  
  42.             android:gravity="center"  
  43.             android:layout_width="wrap_content"  
  44.             android:layout_height="match_parent"  
  45.             android:textSize="18sp"  
  46.             android:text="取消"  
  47.             android:textColor="@color/white"/>  
  48.   
  49.     </LinearLayout>  
  50.   
  51.     <RelativeLayout  
  52.         android:layout_width="match_parent"  
  53.         android:layout_height="match_parent">  
  54.   
  55.         <LinearLayout  
  56.             android:orientation="vertical"  
  57.             android:id="@+id/search_content_show_ll"  
  58.             android:layout_width="match_parent"  
  59.             android:layout_height="wrap_content">  
  60.         </LinearLayout>  
  61.   
  62.     </RelativeLayout>  
  63.   
  64. </LinearLayout></span>  


因为是将搜索的历史信息做成显示隐藏的效果,所以单独写了一个历史信息的layout:

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.   
  6.     <LinearLayout  
  7.         android:orientation="vertical"  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="wrap_content">  
  10.   
  11.         <ListView  
  12.             android:id="@+id/search_records_lv"  
  13.             android:layout_width="match_parent"  
  14.             android:layout_height="wrap_content"/>  
  15.   
  16.         <View  
  17.             android:layout_width="match_parent"  
  18.             android:layout_height="0.1dp"  
  19.             android:background="@color/custom_gray"/>  
  20.   
  21.         <TextView  
  22.             android:background="@color/white"  
  23.             android:id="@+id/clear_all_records_tv"  
  24.             android:layout_width="match_parent"  
  25.             android:layout_height="40dp"  
  26.             android:textSize="16sp"  
  27.             android:gravity="center"  
  28.             android:textColor="@color/clear_red"  
  29.             android:text="清除历史记录"/>  
  30.   
  31.         <View  
  32.             android:layout_width="match_parent"  
  33.             android:layout_height="0.1dp"  
  34.             android:background="@color/custom_gray"/>  
  35.   
  36.     </LinearLayout>  
  37.   
  38. </LinearLayout>  

既然用到了listview来显示历史搜索信息,就需要写listview的item:

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.   
  6.     <LinearLayout  
  7.         android:background="@color/white"  
  8.         android:orientation="horizontal"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="40dp">  
  11.   
  12.         <TextView  
  13.             android:id="@+id/search_content_tv"  
  14.             android:layout_width="match_parent"  
  15.             android:layout_height="wrap_content"  
  16.             android:drawableLeft="@mipmap/search_icon"  
  17.             android:drawablePadding="8dp"  
  18.             android:layout_margin="10dp"  
  19.             android:layout_gravity="center_vertical"  
  20.         />  
  21.   
  22.     </LinearLayout>  
  23.   
  24. </LinearLayout>  

用到了listview,当然还需要适配器,因为目前只有文本可以使用SimpleAdapter,为了以后能添加别的,我还是自定义了一个Adapter:

[java] view plain copy
  1. /** 
  2.  * Created by 05 on 2016/7/27. 
  3.  */  
  4. public class SearchRecordsAdapter extends BaseAdapter {  
  5.   
  6.     private Context context;  
  7.     private List<String> searchRecordsList;  
  8.     private LayoutInflater inflater;  
  9.   
  10.     public SearchRecordsAdapter(Context context, List<String> searchRecordsList) {  
  11.         this.context = context;  
  12.         this.searchRecordsList = searchRecordsList;  
  13.         inflater = LayoutInflater.from(context);  
  14.     }  
  15.   
  16.     @Override  
  17.     public int getCount() {  
  18.         return searchRecordsList.size() == 0 ? 0 : searchRecordsList.size();  
  19.     }  
  20.   
  21.     @Override  
  22.     public Object getItem(int position) {  
  23.         return searchRecordsList.size() == 0 ? null : searchRecordsList.get(position);  
  24.     }  
  25.   
  26.     @Override  
  27.     public long getItemId(int position) {  
  28.         return position;  
  29.     }  
  30.   
  31.     @Override  
  32.     public View getView(int position, View convertView, ViewGroup parent) {  
  33.         ViewHolder viewHolder;  
  34.         if(null == convertView){  
  35.             viewHolder = new ViewHolder();  
  36.             convertView = inflater.inflate(R.layout.saerch_records_list_item,null);  
  37.             viewHolder.recordTv = (TextView) convertView.findViewById(R.id.search_content_tv);  
  38.   
  39.             convertView.setTag(viewHolder);  
  40.         }else{  
  41.             viewHolder = (ViewHolder) convertView.getTag();  
  42.         }  
  43.   
  44.         String content = searchRecordsList.get(position);  
  45.         viewHolder.recordTv.setText(content);  
  46.   
  47.         return convertView;  
  48.     }  
  49.   
  50.     private class ViewHolder {  
  51.         TextView recordTv;  
  52.     }  
  53. }  

最后就是界面代码了:

[java] view plain copy
  1. /** 
  2.  * 搜索界面 
  3.  * Created by 05 on 2016/7/26. 
  4.  */  
  5. public class SearchContentActivity extends BaseActivity implements View.OnClickListener {  
  6.     private EditText searchContentEt;  
  7.     private SearchRecordsAdapter recordsAdapter;  
  8.     private View recordsHistoryView;  
  9.     private ListView recordsListLv;  
  10.     private TextView clearAllRecordsTv;  
  11.     private LinearLayout searchRecordsLl;  
  12.   
  13.     private List<String> searchRecordsList;  
  14.     private List<String> tempList;  
  15.     private RecordsDao recordsDao;  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         BaseSetContentView(R.layout.activity_search_content);  
  21.   
  22.         initView();  
  23.         initData();  
  24.         bindAdapter();  
  25.         initListener();  
  26.     }  
  27.   
  28.     private void initView() {  
  29.         setHideHeader();  
  30.         initRecordsView();  
  31.   
  32.         searchRecordsLl = (LinearLayout) findViewById(R.id.search_content_show_ll);  
  33.         searchContentEt = (EditText) findViewById(R.id.input_search_content_et);  
  34.   
  35.         //添加搜索view  
  36.         searchRecordsLl.addView(recordsHistoryView);  
  37.   
  38.     }  
  39.   
  40.     //初始化搜索历史记录View  
  41.     private void initRecordsView() {  
  42.         recordsHistoryView = LayoutInflater.from(this).inflate(R.layout.search_records_list_layout, null);  
  43.         //显示历史记录lv  
  44.         recordsListLv = (ListView) recordsHistoryView.findViewById(R.id.search_records_lv);  
  45.         //清除搜索历史记录  
  46.         clearAllRecordsTv = (TextView) recordsHistoryView.findViewById(R.id.clear_all_records_tv);  
  47.     }  
  48.   
  49.   
  50.     private void initData() {  
  51.         recordsDao = new RecordsDao(this);  
  52.         searchRecordsList = new ArrayList<>();  
  53.         tempList = new ArrayList<>();  
  54.         tempList.addAll(recordsDao.getRecordsList());  
  55.   
  56.         reversedList();  
  57.         //第一次进入判断数据库中是否有历史记录,没有则不显示  
  58.         checkRecordsSize();  
  59.     }  
  60.   
  61.   
  62.     private void bindAdapter() {  
  63.         recordsAdapter = new SearchRecordsAdapter(this, searchRecordsList);  
  64.         recordsListLv.setAdapter(recordsAdapter);  
  65.     }  
  66.   
  67.     private void initListener() {  
  68.         clearAllRecordsTv.setOnClickListener(this);  
  69.         searchContentEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {  
  70.   
  71.             @Override  
  72.             public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
  73.                 if (actionId == EditorInfo.IME_ACTION_SEARCH) {  
  74.                     if (searchContentEt.getText().toString().length() > 0) {  
  75.   
  76.                         String record = searchContentEt.getText().toString();  
  77.   
  78.                         //判断数据库中是否存在该记录  
  79.                         if (!recordsDao.isHasRecord(record)) {  
  80.                             tempList.add(record);  
  81.                         }  
  82.                         //将搜索记录保存至数据库中  
  83.                         recordsDao.addRecords(record);  
  84.                         reversedList();  
  85.                         checkRecordsSize();  
  86.                         recordsAdapter.notifyDataSetChanged();  
  87.   
  88.                         //根据关键词去搜索  
  89.                           
  90.                     } else {  
  91.                         ToastUtils.showToast(SearchContentActivity.this"搜索内容不能为空");  
  92.                     }  
  93.                 }  
  94.                 return false;  
  95.             }  
  96.         });  
  97.   
  98.         //根据输入的信息去模糊搜索  
  99.         searchContentEt.addTextChangedListener(new TextWatcher() {  
  100.             @Override  
  101.             public void beforeTextChanged(CharSequence s, int start, int count, int after) {  
  102.   
  103.             }  
  104.   
  105.             @Override  
  106.             public void onTextChanged(CharSequence s, int start, int before, int count) {  
  107.   
  108.             }  
  109.   
  110.             @Override  
  111.             public void afterTextChanged(Editable s) {  
  112.                 String tempName = searchContentEt.getText().toString();  
  113.                 tempList.clear();  
  114.                 tempList.addAll(recordsDao.querySimlarRecord(tempName));  
  115.                 reversedList();  
  116.                 checkRecordsSize();  
  117.                 recordsAdapter.notifyDataSetChanged();  
  118.             }  
  119.         });  
  120.   
  121.         //历史记录点击事件  
  122.         recordsListLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
  123.             @Override  
  124.             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
  125.                 //将获取到的字符串传到搜索结果界面  
  126.   
  127.             }  
  128.         });  
  129.     }  
  130.   
  131.     //当没有匹配的搜索数据的时候不显示历史记录栏  
  132.     private void checkRecordsSize(){  
  133.         if(searchRecordsList.size() == 0){  
  134.             searchRecordsLl.setVisibility(View.GONE);  
  135.         }else{  
  136.             searchRecordsLl.setVisibility(View.VISIBLE);  
  137.         }  
  138.     }  
  139.   
  140.     @Override  
  141.     public void onClick(View v) {  
  142.         switch (v.getId()){  
  143.             //清空所有历史数据  
  144.             case R.id.clear_all_records_tv:  
  145.                 tempList.clear();  
  146.                 reversedList();  
  147.                 recordsDao.deleteAllRecords();  
  148.                 recordsAdapter.notifyDataSetChanged();  
  149.                 searchRecordsLl.setVisibility(View.GONE);  
  150.                 break;  
  151.         }  
  152.     }  
  153.   
  154.     //颠倒list顺序,用户输入的信息会从上依次往下显示  
  155.     private void reversedList(){  
  156.         searchRecordsList.clear();  
  157.         for(int i = tempList.size() - 1 ; i >= 0 ; i --){  
  158.             searchRecordsList.add(tempList.get(i));  
  159.         }  
  160.     }  
  161. }  

以上就是实现搜索记录存储,搜索信息模糊查询的全部代码了,供大家参考,当然也给自己提供一个整理思路的锻炼。
  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值