Auto-match keyword and marked red, match keyword marked red
1. single keyword matching
The Code is as follows:
if (name != null && name.contains(mKeyWord)) { int index = name.indexOf(mKeyWord); int len = mKeyWord.length(); Spanned temp = Html.fromHtml(name.substring(0, index) + "<font color=#FF0000>" + name.substring(index, index + len) + "</font>" + name.substring(index + len, name.length())); holder.tv_name.setText(temp); } else { holder.tv_name.setText(name); }
The above name is the content of the entire item to be displayed, and mKeyWord is the search keyword holder. TV _name is the current textview control.
2. Multi-Keyword matching
Sometimes we need to split the keywords entered by users on the server and split them into multiple keywords for search. The keywords returned by the server are split into multiple keywords. That is, an array of keywords is returned.
In this case, we need to write an algorithm to match and mark all the keywords in the section when the client matches the keywords.
The Code is as follows:
Logic in the adapter:
/** Name is the item display content the current item display string content keyList refers to the list set storing multiple keywords */StringBuffer str = new StringBuffer (""); str = Utils. addChild (name, keyList, str); holder. contentTv. setText (Html. fromHtml (str. toString ()));
/*** Multi-Keyword query table red, avoid the following keywords as special HTML code * @ param str retrieval result * @ param inputs keyword Set * @ param resStr table red result */public static StringBuffer addChild (String str, list <String> inputs, StringBuffer resStr) {int index = str. length (); // used as the identifier to determine the subscript of the keyword String next = ""; // Save the first keyword in str for (int I = inputs. size ()-1; I> = 0; I --) {String theNext = inputs. get (I); int theIndex = str. indexOf (theNext); if (theIndex =-1) {// filter out the invalid keyword inputs. remove (I) ;}else if (theIndex <index) {index = theIndex; // Replace the subscript next = theNext ;}// if the condition is true, indicates that no keyword can be replaced in the string; otherwise, if (index = str. length () {resStr. append (str);} else {resStr. append (str. substring (0, index); resStr. append ("<font color = '# FF0000'>" + str. substring (index, index + next. length () + "</font>"); String str1 = str. substring (index + next. length (), str. length (); addChild (str1, inputs, resStr); // Replace the remaining strings} return resStr ;}