核心逻辑方法:
/** * 搜索item * @param searchContent 需要搜索的文本内容 */ public void searchItem(String searchContent){ this.mSearchContent = searchContent.trim();//去除空格 if(TextUtils.isEmpty(mSearchContent)||mSearchContent.length()==0){//如果搜索内容是空的就显示全部内容 this.mShowList.clear(); mShowList.addAll(mAllDataList); notifyDataSetChanged(); return; } List<THealthDataListBase.StudentData> tempList = new ArrayList<>();//用于临时保存匹配完成的数据 THealthDataListBase.StudentData tempStudentData = null;//用于临时保存匹配完成的item数据 char[] searchContentCharArray = searchContent.toCharArray(); for (THealthDataListBase.StudentData studentData : mAllDataList){ //遍历全部学生名称 char[] studentNameCharArray = studentData.name.trim().toCharArray();//学生名称去除空格,并且转成数组 int count = 0; for (int i=0;i<searchContentCharArray.length;i++){ //遍历搜索文字 for (char word :studentNameCharArray){ //遍历学生名称文字 if (word == searchContentCharArray[i]){ //判断一致的文字 count++; } } } if (count == 0){ //如果匹配度是0就不添加 continue; } tempStudentData = new THealthDataListBase().new StudentData(); tempStudentData.name = studentData.name; tempStudentData.studentId = studentData.studentId; tempStudentData.morning = studentData.morning; tempStudentData.noon = studentData.noon; tempStudentData.setCount(count); tempList.add(tempStudentData); } if (tempList.isEmpty() && !mSearchContent.isEmpty()){ mShowList.clear(); notifyDataSetChanged(); return; } Collections.sort(tempList);//排序 mShowList.clear(); mShowList.addAll(tempList); notifyDataSetChanged(); }