Android搜索关键字高亮显示
程序员文章站
2022-07-14 10:48:12
...
需求分析:根据搜索的关键字,让关键字在查询到的内容里高亮显示出来。
先给大家看一下效果图:
这里也分享一下Demo源代码的下载地址:
https://download.csdn.net/download/qq15577969/10669001
一、首先从网上找了个文字变色的工具类 KeyWordUtil.java
package com.t20.searchdemo.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
/**
* 文字变色工具类
*/
public class KeyWordUtil {
/**
* 关键字高亮变色
*
* @param color 变化的色值
* @param text 文字
* @param keyword 文字中的关键字
* @return 结果SpannableString
*/
public static SpannableString matcherSearchTitle(int color, String text, String keyword) {
SpannableString s = new SpannableString(text);
keyword=escapeExprSpecialWord(keyword);
text=escapeExprSpecialWord(text);
if (text.contains(keyword)&&!TextUtils.isEmpty(keyword)){
try {
Pattern p = Pattern.compile(keyword);
Matcher m = p.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
s.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}catch (Exception e){
}
}
return s;
}
/**
* 转义正则特殊字符 ($()*+.[]?\^{},|)
*
* @param keyword
* @return keyword
*/
public static String escapeExprSpecialWord(String keyword) {
if (!TextUtils.isEmpty(keyword)) {
String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
for (String key : fbsArr) {
if (keyword.contains(key)) {
keyword = keyword.replace(key, "\\" + key);
}
}
}
return keyword;
}
}
二、另外重写了一个带有删除功能的EditText输入框 ClearEditText.java
package com.t20.searchdemo.view;
import com.t20.searchdemo.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.Toast;
public class ClearEditText extends EditText implements OnFocusChangeListener, TextWatcher {
/**
* 删除按钮的引用
*/
private Drawable mClearDrawable;
/**
* 控件是否有焦点
*/
private boolean hasFoucs;
private boolean isShow = false;
public ClearEditText(Context context) {
this(context, null);
}
public ClearEditText(Context context, AttributeSet attrs) {
//这里构造方法也很重要,不加这个很多属性不能再XML里面定义
this(context, attrs, android.R.attr.editTextStyle);
}
public ClearEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
//获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,getCompoundDrawables()获取Drawable的四个位置的数组
mClearDrawable = getCompoundDrawables()[2];
if (mClearDrawable == null) {
mClearDrawable = getResources().getDrawable(R.drawable.icon_del);
// throw new NullPointerException("You can add drawableRight attribute in XML");
}
//设置图标的位置以及大小,getIntrinsicWidth()获取显示出来的大小而不是原图片的带小
mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());
//默认设置隐藏图标
setClearIconVisible(false);
//设置焦点改变的监听
setOnFocusChangeListener(this);
//设置输入框里面内容发生改变的监听
addTextChangedListener(this);
}
/**
* 因为我们不能直接给EditText设置点击事件,所以我们用记住我们按下的位置来模拟点击事件
* 当我们按下的位置 在 EditText的宽度 - 图标到控件右边的间距 - 图标的宽度 和
* EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标,竖直方向就没有考虑
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (getCompoundDrawables()[2] != null) {
//getTotalPaddingRight()图标左边缘至控件右边缘的距离
//getWidth() - getTotalPaddingRight()表示从最左边到图标左边缘的位置
//getWidth() - getPaddingRight()表示最左边到图标右边缘的位置
boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
&& (event.getX() < ((getWidth() - getPaddingRight())));
if (touchable) {
this.setText("");
}
}
// if(getCompoundDrawables()[0] != null){
// boolean touchLeft = event.getX()>0 && event.getX()<getCompoundDrawables()[0].getIntrinsicWidth();
// if(touchLeft){
// if(isShow==false){
// isShow = true;
// //设置为可见
// this.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
// }else{
// isShow = false;
// //设置为密码模式
// this.setTransformationMethod(PasswordTransformationMethod.getInstance());
// }
// }
// }
}
return super.onTouchEvent(event);
}
/**
* 当ClearEditText焦点发生变化的时候,判断里面字符串长度设置清除图标的显示与隐藏
*/
@Override
public void onFocusChange(View v, boolean hasFocus) {
this.hasFoucs = hasFocus;
if (hasFocus) {
setClearIconVisible(getText().length() > 0);
} else {
setClearIconVisible(false);
}
}
/**
* 设置清除图标的显示与隐藏,调用setCompoundDrawables为EditText绘制上去
* @param visible
*/
protected void setClearIconVisible(boolean visible) {
Drawable right = visible ? mClearDrawable : null;
setCompoundDrawables(getCompoundDrawables()[0],
getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
}
/**
* 当输入框里面内容发生变化的时候回调的方法
*/
@Override
public void onTextChanged(CharSequence s, int start, int count,
int after) {
if(hasFoucs){
setClearIconVisible(s.length() > 0);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
/**
* 设置晃动动画
*/
public void setShakeAnimation(){
this.startAnimation(shakeAnimation(5));
}
/**
* 晃动动画
* @param counts 1秒钟晃动多少下
* @return
*/
public static Animation shakeAnimation(int counts){
Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
translateAnimation.setInterpolator(new CycleInterpolator(counts));
translateAnimation.setDuration(1000);
return translateAnimation;
}
}
三、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:background="#fff"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F0F0F0"
android:orientation="horizontal"
android:padding="5dp" >
<Button
android:id="@+id/search_btn_2wm"
android:layout_width="32dp"
android:layout_height="32dp"
android:alpha="0.7"
android:background="@drawable/icon_qrcode" />
<com.t20.searchdemo.view.ClearEditText
android:id="@+id/search_editText_searchContent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#fff"
android:drawableLeft="@drawable/icon_search"
android:drawablePadding="5dp"
android:ems="10"
android:hint="输入要搜索的ID或名称"
android:maxLines="1"
android:padding="5dp"
android:textColor="#ff9314"
android:textSize="13sp" >
</com.t20.searchdemo.view.ClearEditText>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="5dp" >
<Button
android:id="@+id/search_btn_back"
android:layout_width="30dp"
android:layout_height="35dp"
android:alpha="0.7"
android:background="@drawable/icon_right_back" />
<TextView
android:id="@+id/search_tv_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="搜索"
android:textColor="#FF9316"
android:textSize="13sp"
android:visibility="gone" />
</FrameLayout>
</LinearLayout>
<ListView
android:id="@+id/search_listView_search_result"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
search_listview_item.xml 布局,这个是ListView的子项布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:orientation="horizontal" >
<ImageView
android:id="@+id/search_listView_item_iv_userHeadPic"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/head_default" />
<TextView
android:id="@+id/search_listView_item_tv_userNumber"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:textSize="16sp"
android:gravity="center"
android:textColor="#666"
android:text="123456" />
<TextView
android:id="@+id/search_listView_item_tv_userNick"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:textSize="16sp"
android:gravity="center"
android:textColor="#666"
android:text="匿名用户" />
</LinearLayout>
四、活动 MainActivity.ajva 的代码如下:
package com.t20.searchdemo;
import java.util.ArrayList;
import java.util.List;
import com.t20.searchdemo.adapter.SearchListViewAdapter;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class MainActivity extends Activity implements OnClickListener {
//返回按钮(关闭)
private Button mButtonBack;
//输入框
private EditText mEditTextSearchContent;
//搜索按钮
private TextView mTextViewSearch;
//用户输入的搜索内容
private String searchContent;
//显示搜索内容的ListView
private ListView mListViewSearchResult;
//用户集合
private List<User> mUserList;
//ListView的适配器
private SearchListViewAdapter mSearchListViewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 1、隐藏标题栏,在加载布局之前设置(兼容Android2.3.3版本)
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 2、隐藏状态栏
//getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
initView();
initEvent();
}
private void initEvent() {
// TODO Auto-generated method stub
////点击输入法软键盘回车键时,也可以直接查询
mEditTextSearchContent.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (!TextUtils.isEmpty(mEditTextSearchContent.getText())) {
// 保持光标在输入框最后
mEditTextSearchContent.setSelection(mEditTextSearchContent.getText().length());
}
//当actionId == XX_SEND 或者 XX_DONE时都触发
//或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
//注意,这是一定要判断event != null。因为在某些输入法上会返回null。
if (actionId == EditorInfo.IME_ACTION_SEND
|| actionId == EditorInfo.IME_ACTION_DONE
|| (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
//点击输入法软键盘回车键时,进行查询
search();
}
return true;//为true表示自己消费该事件
}
});
}
private void initView() {
// TODO Auto-generated method stub
mButtonBack=(Button) findViewById(R.id.search_btn_back);
mEditTextSearchContent=(EditText) findViewById(R.id.search_editText_searchContent);
mTextViewSearch=(TextView) findViewById(R.id.search_tv_search);
mListViewSearchResult=(ListView) findViewById(R.id.search_listView_search_result);
//设置监听
mButtonBack.setOnClickListener(this);
mTextViewSearch.setOnClickListener(this);
mEditTextSearchContent.setOnClickListener(this);
mEditTextSearchContent.addTextChangedListener(textWatcher);
}
private TextWatcher textWatcher=new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable editable) {
// TODO Auto-generated method stub
//获取输入框内容
String content=mEditTextSearchContent.getText().toString();
//输入框内容为空时,显示返回按钮,隐藏搜索按钮
if(content.isEmpty()){
mTextViewSearch.setVisibility(View.GONE);
mButtonBack.setVisibility(View.VISIBLE);
mListViewSearchResult.setVisibility(View.GONE);
}else{
mTextViewSearch.setVisibility(View.VISIBLE);
mButtonBack.setVisibility(View.GONE);
mListViewSearchResult.setVisibility(View.VISIBLE);
}
}
};
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
//点击搜索框
case R.id.search_editText_searchContent:
mEditTextSearchContent.setFocusable(true);
mEditTextSearchContent.setFocusableInTouchMode(true);
mEditTextSearchContent.requestFocus();
InputMethodManager imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditTextSearchContent, 0);
break;
//关闭按钮
case R.id.search_btn_back:
finish();
break;
//点击搜索
case R.id.search_tv_search:
search();
break;
}
}
/**
* 搜索数据
*/
private void search() {
// TODO Auto-generated method stub
//获取用户搜索的内容
searchContent=mEditTextSearchContent.getText().toString();
//初始化一些数据(实际开发中,是去数据库中读取)
mUserList=new ArrayList<MainActivity.User>();
User u1=new User(1, "4346546", "张三");
User u2=new User(1, "3346565", "李四");
User u3=new User(1, "6865879", "王五");
User u4=new User(1, "5745786", "赵六");
mUserList.add(u1);
mUserList.add(u2);
mUserList.add(u3);
mUserList.add(u4);
//设置适配器
mSearchListViewAdapter=new SearchListViewAdapter(MainActivity.this, mUserList, searchContent);
mListViewSearchResult.setAdapter(mSearchListViewAdapter);
}
/**
* 自定义一个用户类
*/
public class User {
Integer id; //Id
String number;//账号
String nick; //昵称
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public User() {
super();
}
public User(Integer id, String number, String nick) {
super();
this.id = id;
this.number = number;
this.nick = nick;
}
}
}
五、自定义的 SearchListViewAdapter.java 适配器
package com.t20.searchdemo.adapter;
import java.util.List;
import com.t20.searchdemo.MainActivity.User;
import com.t20.searchdemo.R;
import com.t20.searchdemo.util.KeyWordUtil;
import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SearchListViewAdapter extends BaseAdapter {
private Context context;
private List<User> mUserList;
private String searchContent;//用户搜索的内容
public SearchListViewAdapter(Context context,
List<User> mUserList, String searchContent) {
super();
this.context = context;
this.mUserList = mUserList;
this.searchContent = searchContent;
}
public void setSearchContent(String searchContent) {
this.searchContent = searchContent;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mUserList.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//获得对象
User user=mUserList.get(position);
//加载布局
View view;
ViewHolder viewHolder;
if(convertView==null){
view=LayoutInflater.from(context).inflate(R.layout.search_listview_item,null);
viewHolder=new ViewHolder();
//获取控件
viewHolder.textViewNumber=(TextView) view.findViewById(R.id.search_listView_item_tv_userNumber);
viewHolder.textViewNick=(TextView) view.findViewById(R.id.search_listView_item_tv_userNick);
//将ViewHolder存储在View中
view.setTag(viewHolder);
}else{
view=convertView;
//重新获取ViewHolder
viewHolder=(ViewHolder) view.getTag();
}
//设置控件的值
//搜索高亮显示
if(user.getNumber()!=null&&user.getNumber().length()>0){
SpannableString number=KeyWordUtil.matcherSearchTitle(Color.parseColor("#ff9314"), user.getNumber()+"", searchContent);
viewHolder.textViewNumber.setText(number);
}
if(user.getNick()!=null&&user.getNick().length()>0){
SpannableString nick=KeyWordUtil.matcherSearchTitle(Color.parseColor("#ff9314"), user.getNick(), searchContent);
viewHolder.textViewNick.setText(nick);
}
return view;
}
class ViewHolder{
TextView textViewNumber;
TextView textViewNick;
}
}
上一篇: elasticsearch搜素关键字自动补全(suggest)
下一篇: vue实现搜索关键字高亮