2
你以爲我有這個字符串,它與某些標籤格式之間的所有文字:Android的着色標記
String content = "11111<mft:A>22222</mft:A>111111<mft:R>33333<mft:A>22222</mft:A>333333<mft:S>444444</mft:S></mft:R><mft:A>2222222</mft:A>";
我想上色這個字符串像這個屏幕截圖中提取標籤:
不幸的是我寫的代碼不正確,無法在標籤之間正確着色:
我的結果代碼:
下面這是我的代碼不正確的標籤之間上色文本
private List<AyehaTagsInformation> ayeHaPositions = new ArrayList<>();
private List<AsharTagsInformation> sherHaPositions = new ArrayList<>();
private List<RevayatTagsInformation> revayatHaPositions = new ArrayList<>();
private void extractTags(String str) {
Pattern mftA_REGEX = Pattern.compile("<mft:A>(.+?)</mft:A>");
Pattern mftR_REGEX = Pattern.compile("<mft:R>(.+?)</mft:R>");
Pattern mftS_REGEX = Pattern.compile("<mft:S>(.+?)</mft:S>");
Matcher matcher = mftA_REGEX.matcher(str);
while (matcher.find()) {
ayeHaPositions.add(new AyehaTagsInformation(matcher.start(1), matcher.end(1)));
}
matcher = mftR_REGEX.matcher(str);
while (matcher.find()) {
revayatHaPositions.add(new RevayatTagsInformation(matcher.start(1), matcher.end(1)));
}
matcher = mftS_REGEX.matcher(str);
while (matcher.find()) {
sherHaPositions.add(new AsharTagsInformation(matcher.start(1), matcher.end(1)));
}
}
String content = "11111<mft:A>22222</mft:A>111111<mft:R>33333<mft:A>22222</mft:A>333333<mft:S>444444</mft:S></mft:R><mft:A>2222222</mft:A>";
extractTags(content);
Spannable wordToSpan = new SpannableStringBuilder(content);
if (revayatHaPositions.size() > 0) {
for (int p = 0; p < revayatHaPositions.size(); p++) {
try {
wordToSpan.setSpan(new ForegroundColorSpan(Color.GREEN), revayatHaPositions.get(p).getStart(), revayatHaPositions.get(p).getEnd(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
e.printStackTrace();
Log.e("Error colorize: ", e.getMessage());
}
}
}
if (ayeHaPositions.size() > 0) {
for (int p = 0; p < ayeHaPositions.size(); p++) {
try {
wordToSpan.setSpan(new ForegroundColorSpan(Color.BLUE), ayeHaPositions.get(p).getStart(), ayeHaPositions.get(p).getEnd(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
e.printStackTrace();
Log.e("Error colorize: ", e.getMessage());
}
}
}
if (sherHaPositions.size() > 0) {
for (int p = 0; p < sherHaPositions.size(); p++) {
try {
wordToSpan.setSpan(new ForegroundColorSpan(Color.RED), sherHaPositions.get(p).getStart(), sherHaPositions.get(p).getEnd(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
e.printStackTrace();
Log.e("Error colorize: ", e.getMessage());
}
}
}
message.setText(wordToSpan);
Android不支持嵌套的標籤''html tag –
先生,我已經在Android 6.0上驗證過,請驗證 –
請嘗試下面的代碼:'String s3 =「 111111 2222「;' –