Last active
August 29, 2015 14:06
-
-
Save takke/89a50ba249289e5d7491 to your computer and use it in GitHub Desktop.
replaceHashtagMentions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ハッシュタグやメンションを置換する | |
* | |
* @param html | |
* @param targets | |
* @return | |
*/ | |
private static String replaceHashtagMentions(String html, final ArrayList<HashtagMentionEntity> targets) { | |
// 先に出てくる順にソート | |
// ※HashtagEntityとUserMentionEntityを混ぜているので出現順にソートする | |
if (targets != null && targets.size() >= 2) { | |
Collections.sort(targets, new Comparator<HashtagMentionEntity>() { | |
@Override | |
public int compare(HashtagMentionEntity lhs, HashtagMentionEntity rhs) { | |
final int s1 = lhs.getStart(); | |
final int s2 = rhs.getStart(); | |
if (s1 > s2) { | |
return 1; | |
} | |
if (s1 < s2) { | |
return -1; | |
} | |
final int e1 = lhs.getEnd(); | |
final int e2 = rhs.getEnd(); | |
if (e1 > e2) { | |
return 1; | |
} | |
if (e1 < e2) { | |
return -1; | |
} | |
return rhs.getText().compareTo(lhs.getText()); | |
} | |
}); | |
} | |
if (targets != null && targets.size() >= 1) { | |
int gap = 0; // 置換済み文字列分のインデックス移動分(累積) | |
final String lv = "<font color=\"" + ThemeColor.urlColorCss + "\">"; | |
final String rv = "</font>"; | |
final int oneGap = lv.length() + rv.length(); | |
for (HashtagMentionEntity e : targets) { | |
// start は # のインデックス | |
// end は ハッシュタグ終了文字の次の文字のインデックス | |
final int start = e.getStart() + gap; | |
final int end = e.getEnd() + gap; | |
try { | |
// サロゲートペア文字で飛ぶことがあるのでCodePointベースで範囲計算する | |
// @see http://www.ibm.com/developerworks/jp/java/library/j-unicode/ | |
final int[] chars = TPUtil.toCodePointArray(html); | |
html = new String(chars, 0, start) | |
+ lv | |
+ new String(chars, start, end-start) | |
+ rv | |
+ new String(chars, end, chars.length-end); | |
} catch (StringIndexOutOfBoundsException ex) { | |
MyLog.e(ex); | |
} catch (IndexOutOfBoundsException ex) { | |
MyLog.e(ex); | |
} | |
gap += oneGap; | |
} | |
} | |
return html; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment