
public static SpannableString matcherSearchTitle(int color, String text,
String keyword) {
List strings = new ArrayList();
SpannableString s = new SpannableString(text);
if (keyword.length() == 1) {
Pattern p = Pattern.compile(escapeExprSpecialWord(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);
}
} else {
for (int i = 0; i < keyword.length(); i++) {
if (i == keyword.length()) {
String substring = keyword.substring(i);
strings.add(substring);
} else {
String substring = keyword.substring(i, i + 1);
strings.add(substring);
}
}
for (int i = 0; i < keyword.length(); i++) {
Pattern p = Pattern.compile(escapeExprSpecialWord(strings.get(i)));
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);
}
}
}
return s;
}
private static String escapeExprSpecialWord(String keyword) {
String[] fbsArr = {"\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|"};
for (String key : fbsArr) {
if (keyword.contains(key)) {
keyword = keyword.replace(key, "\" + key);
}
}
return keyword;
}
使用方式
KeywordUtil.matcherSearchTitle(Color.RED, "所有字", "需要高亮的关键字");EditTextUtils 工具类
public class EditTextUtils {
public static boolean isShouldHideSoftKeyBoard(View view, MotionEvent event) {
if (view != null && (view instanceof EditText)) {
int[] l = { 0, 0 };
view.getLocationInWindow(l);
int left = l[0], top = l[1], bottom = top + view.getHeight(), right = left + view.getWidth();
if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
// If click the EditText event ,ignore it
return false;
} else {
return true;
}
}
// if the focus is EditText,ignore it;
return false;
}
public static void hideSoftKeyBoard(IBinder token, Context context) {
if (token != null) {
InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
//禁止EditText输入空格
public static InputFilter filter = (source, start, end, dest, dstart, dend) -> {
if (source.equals(" ")){
return "";
} else return null;
};