android 搜索时关键字变色

/**
 * 关键字变色
 */
public SpannableStringBuilder putstr(String keyword, String strtext, Context context) {
    String docInfo = strtext;
    int keywordIndex = strtext.indexOf(keyword);
    SpannableStringBuilder style = new SpannableStringBuilder(docInfo);
    while (keywordIndex != -1) {
        /**
         * 关键字颜色改变
         */
        style.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.dark_green)), keywordIndex, keywordIndex + keyword.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        int tempkeywordTempIndex = keywordIndex + keyword.length();
        strtext = docInfo.substring(tempkeywordTempIndex, docInfo.length());
        keywordIndex = strtext.indexOf(keyword);
        if (keywordIndex != -1) {
            keywordIndex = keywordIndex + tempkeywordTempIndex;
        }
    }
    return style;

}

你可能感兴趣的:(java/android)