下面列出了android.text.style.ScaleXSpan#android.text.style.BackgroundColorSpan 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void endCssStyle(Editable text) {
Strikethrough s = getLast(text, Strikethrough.class);
if (s != null) {
setSpanFromMark(text, s, new StrikethroughSpan());
}
Background b = getLast(text, Background.class);
if (b != null) {
setSpanFromMark(text, b, new BackgroundColorSpan(b.mBackgroundColor));
}
Foreground f = getLast(text, Foreground.class);
if (f != null) {
setSpanFromMark(text, f, new ForegroundColorSpan(f.mForegroundColor));
}
}
/**
* Equivalent to {@link #setComposingTextInternal(CharSequence, int)} except that this method
* allows to set {@link BackgroundColorSpan} to the composing text with the given color.
*
* <p>TODO: Currently the background color is exclusive with the black underline, which is
* automatically added by the framework. We need to change the framework if we need to have both
* of them at the same time.</p>
* <p>TODO: Should we move this method to {@link RichInputConnection}?</p>
*
* @param newComposingText the composing text to be set
* @param newCursorPosition the new cursor position
* @param backgroundColor the background color to be set to the composing text. Set
* {@link Color#TRANSPARENT} to disable the background color.
* @param coloredTextLength the length of text, in Java chars, which should be rendered with
* the given background color.
*/
private void setComposingTextInternalWithBackgroundColor(final CharSequence newComposingText,
final int newCursorPosition, final int backgroundColor, final int coloredTextLength) {
final CharSequence composingTextToBeSet;
if (backgroundColor == Color.TRANSPARENT) {
composingTextToBeSet = newComposingText;
} else {
final SpannableString spannable = new SpannableString(newComposingText);
final BackgroundColorSpan backgroundColorSpan =
new BackgroundColorSpan(backgroundColor);
final int spanLength = Math.min(coloredTextLength, spannable.length());
spannable.setSpan(backgroundColorSpan, 0, spanLength,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING);
composingTextToBeSet = spannable;
}
mConnection.setComposingText(composingTextToBeSet, newCursorPosition);
}
private void presentAnswer(QaAnswer answer) {
// Highlight answer.
Spannable spanText = new SpannableString(content);
int offset = content.indexOf(answer.text, 0);
if (offset >= 0) {
spanText.setSpan(
new BackgroundColorSpan(getColor(R.color.secondaryColor)),
offset,
offset + answer.text.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
contentTextView.setText(spanText);
// Use TTS to speak out the answer.
if (textToSpeech != null) {
textToSpeech.speak(answer.text, TextToSpeech.QUEUE_FLUSH, null, answer.text);
}
}
private static void endCssStyle(Editable text) {
Strikethrough s = getLast(text, Strikethrough.class);
if (s != null) {
setSpanFromMark(text, s, new JerryStrikeThroughSpan());
}
Background b = getLast(text, Background.class);
if (b != null) {
setSpanFromMark(text, b, new BackgroundColorSpan(b.mBackgroundColor));
}
Foreground f = getLast(text, Foreground.class);
if (f != null) {
setSpanFromMark(text, f, new ForegroundColorSpan(f.mForegroundColor));
}
}
@SuppressWarnings("ConstantConditions")
private void initSms() {
if (sms != null) {
SmsParser smsParser = new SmsParser(sms, getApplicationContext());
Spannable text = new SpannableString(sms.getmBody());
text.setSpan(new BackgroundColorSpan(ContextCompat.getColor(this, R.color.ColorAccount)), smsParser.mAccountBorders.first, smsParser.mAccountBorders.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new BackgroundColorSpan(ContextCompat.getColor(this, R.color.ColorAmount)), smsParser.mAmountBorders.first, smsParser.mAmountBorders.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new BackgroundColorSpan(ContextCompat.getColor(this, R.color.ColorAmount)), smsParser.mBalanceBorders.first, smsParser.mBalanceBorders.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new BackgroundColorSpan(ContextCompat.getColor(this, R.color.ColorPayee)), smsParser.mPayeeBorders.first, smsParser.mPayeeBorders.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new BackgroundColorSpan(ContextCompat.getColor(this, R.color.ColorDestAccount)), smsParser.mDestAccountBorders.first, smsParser.mDestAccountBorders.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new BackgroundColorSpan(ContextCompat.getColor(this, R.color.ColorType)), smsParser.mTrTypeBorders.first, smsParser.mTrTypeBorders.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new BackgroundColorSpan(ContextCompat.getColor(this, R.color.ColorCabbage)), smsParser.mCabbageAmountBorders.first, smsParser.mCabbageAmountBorders.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new BackgroundColorSpan(ContextCompat.getColor(this, R.color.ColorCabbage)), smsParser.mCabbageBalanceBorders.first, smsParser.mCabbageBalanceBorders.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
edSms.setText(text);
// imageButtonAddMarker.setImageDrawable(IconGenerator.getInstance(this).getAddIcon(this));
imageButtonAddMarker.setOnClickListener(v -> ActivityEditTransaction.this.showAddMarkerDialog());
edSms.setCustomSelectionActionModeCallback(new ActionModeCallback(this));
} else {
layoutSms.setVisibility(View.GONE);
}
}
/**
* Equivalent to {@link #setComposingTextInternal(CharSequence, int)} except that this method
* allows to set {@link BackgroundColorSpan} to the composing text with the given color.
*
* <p>TODO: Currently the background color is exclusive with the black underline, which is
* automatically added by the framework. We need to change the framework if we need to have both
* of them at the same time.</p>
* <p>TODO: Should we move this method to {@link RichInputConnection}?</p>
*
* @param newComposingText the composing text to be set
* @param newCursorPosition the new cursor position
* @param backgroundColor the background color to be set to the composing text. Set
* {@link Color#TRANSPARENT} to disable the background color.
* @param coloredTextLength the length of text, in Java chars, which should be rendered with
* the given background color.
*/
private void setComposingTextInternalWithBackgroundColor(final CharSequence newComposingText,
final int newCursorPosition, final int backgroundColor, final int coloredTextLength) {
final CharSequence composingTextToBeSet;
if (backgroundColor == Color.TRANSPARENT) {
composingTextToBeSet = newComposingText;
} else {
final SpannableString spannable = new SpannableString(newComposingText);
final BackgroundColorSpan backgroundColorSpan =
new BackgroundColorSpan(backgroundColor);
final int spanLength = Math.min(coloredTextLength, spannable.length());
spannable.setSpan(backgroundColorSpan, 0, spanLength,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING);
composingTextToBeSet = spannable;
}
mConnection.setComposingText(composingTextToBeSet, newCursorPosition);
}
public CharSequence getformatedSearchSnippet() {
//TODO implement improved snippet function
String CleanedSearchString = " " + ArabicUtilities.cleanTextForSearchingWthStingBuilder(searchString) + " ";
StringBuilder cleanedUnformattedPage = new StringBuilder(ArabicUtilities.cleanTextForSearchingWthStingBuilder(unformatedPage));
int firstMatchStart = cleanedUnformattedPage.indexOf(CleanedSearchString);
cleanedUnformattedPage.delete(0, Math.max(firstMatchStart - 100, 0));
cleanedUnformattedPage.delete(
Math.min(firstMatchStart + CleanedSearchString.length() + 100, cleanedUnformattedPage.length())
, cleanedUnformattedPage.length());
cleanedUnformattedPage.insert(0, "...");
cleanedUnformattedPage.append("...");
Spannable snippet = SpannableString.
valueOf(cleanedUnformattedPage.toString());
int index = TextUtils.indexOf(snippet, CleanedSearchString);
while (index >= 0) {
snippet.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
+ CleanedSearchString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
index = TextUtils.indexOf(snippet, CleanedSearchString, index + CleanedSearchString.length());
}
return snippet;
}
@Override public void handleTagNode(TagNode node, SpannableStringBuilder builder, int start, int end) {
if (isPre) {
StringBuffer buffer = new StringBuffer();
buffer.append("\n");//fake padding top + make sure, pre is always by itself
getPlainText(buffer, node);
buffer.append("\n");//fake padding bottom + make sure, pre is always by itself
builder.append(replace(buffer.toString()));
builder.append("\n");
builder.setSpan(new CodeBackgroundRoundedSpan(color), start, builder.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
builder.append("\n");
this.appendNewLine(builder);
this.appendNewLine(builder);
} else {
StringBuffer text = node.getText();
builder.append(" ");
builder.append(replace(text.toString()));
builder.append(" ");
final int stringStart = start + 1;
final int stringEnd = builder.length() - 1;
builder.setSpan(new BackgroundColorSpan(color), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
if (theme == PrefGetter.LIGHT) {
builder.setSpan(new ForegroundColorSpan(Color.RED), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
}
builder.setSpan(new TypefaceSpan("monospace"), stringStart, stringEnd, SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
/**
* Highlights everything that matched the current filter (if any) in text
*
* @param text the text to highlight
* @param color the highlight color
* @return a spannable string
*/
protected Spannable highlight(String text, int color) {
if (text == null) return null;
Spannable highlighted = new SpannableStringBuilder(text);
AdvancedFilter filter = getFilter();
if (filter == null || filter.mPattern == null){
return highlighted;
}
Matcher matcher = filter.mPattern.matcher(text);
while (matcher.find()){
highlighted.setSpan(new BackgroundColorSpan(color), matcher.start(),
matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
return highlighted;
}
protected ColorListPickerDialog createColorPicker(boolean fillColor, int selectedColor) {
ColorListPickerDialog dialog = new ColorListPickerDialog(getContext());
if (!fillColor) {
dialog.setTitle(R.string.format_text_color);
} else {
dialog.setTitle(R.string.format_fill_color);
}
dialog.setSelectedColor(selectedColor);
dialog.setPositiveButton(R.string.action_cancel, null);
dialog.setOnColorChangeListener((ColorListPickerDialog d, int newColorIndex, int color) -> {
if (!fillColor) {
removeSpan(ForegroundColorSpan.class);
setSpan(new ForegroundColorSpan(color));
} else {
removeSpan(BackgroundColorSpan.class);
setSpan(new BackgroundColorSpan(color));
}
d.cancel();
});
return dialog;
}
/**
* Highlights everything that matched the current filter (if any) in text
*
* @param text the text to highlight
* @param color the highlight color
* @return a spannable string
*/
protected Spannable highlight(String text, int color) {
if (text == null) return null;
Spannable highlighted = new SpannableStringBuilder(text);
AdvancedFilter filter = getFilter();
if (filter == null || filter.mPattern == null){
return highlighted;
}
Matcher matcher = filter.mPattern.matcher(text);
while (matcher.find()){
highlighted.setSpan(new BackgroundColorSpan(color), matcher.start(),
matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
return highlighted;
}
public static JsonObject spanToJson(Object span) {
JsonObject ret = new JsonObject();
if (span instanceof ForegroundColorSpan) {
ret.addProperty("type", SPAN_TYPE_FOREGROUND);
ret.addProperty("color", ((ForegroundColorSpan) span).getForegroundColor());
} else if (span instanceof BackgroundColorSpan) {
ret.addProperty("type", SPAN_TYPE_BACKGROUND);
ret.addProperty("color", ((BackgroundColorSpan) span).getBackgroundColor());
} else if (span instanceof StyleSpan) {
ret.addProperty("type", SPAN_TYPE_STYLE);
ret.addProperty("style", ((StyleSpan) span).getStyle());
} else {
return null;
}
return ret;
}
private void endCssStyle(String tag, Editable text) {
Strikethrough s = getLast(text, Strikethrough.class);
if (s != null) {
setSpanFromMark(tag, text, s, new StrikethroughSpan());
}
Background b = getLast(text, Background.class);
if (b != null) {
setSpanFromMark(tag, text, b, new BackgroundColorSpan(b.mBackgroundColor));
}
Foreground f = getLast(text, Foreground.class);
if (f != null) {
setSpanFromMark(tag, text, f, new ForegroundColorSpan(f.mForegroundColor));
}
AbsoluteSize a = getLast(text, AbsoluteSize.class);
if (a != null) {
setSpanFromMark(tag, text, a, new AbsoluteSizeSpan(a.getTextSize()));
}
RelativeSize r = getLast(text, RelativeSize.class);
if (r != null) {
setSpanFromMark(tag, text, r, new RelativeSizeSpan(r.getTextProportion()));
}
}
private static void endCssStyle(Editable text) {
Font font = getLast(text, Font.class);
if (font != null) {
if (font.mFace.equalsIgnoreCase("fontello")) {
setSpanFromMark(text, font, new AssetsTypefaceSpan(App.getContext(), "fontello/fontello.ttf"));
}
}
Strikethrough s = getLast(text, Strikethrough.class);
if (s != null) {
setSpanFromMark(text, s, new StrikethroughSpan());
}
Background b = getLast(text, Background.class);
if (b != null) {
setSpanFromMark(text, b, new BackgroundColorSpan(b.mBackgroundColor));
}
Foreground f = getLast(text, Foreground.class);
if (f != null) {
setSpanFromMark(text, f, new ForegroundColorSpan(f.mForegroundColor));
}
}
private void handleEndTag(CharacterStyle style) {
if (style instanceof URLSpan) {
mOut.append("</a>");
} else if (style instanceof TypefaceSpan) {
mOut.append("</font>");
} else if (style instanceof ForegroundColorSpan) {
mOut.append("</font>");
} else if (style instanceof BackgroundColorSpan) {
mOut.append("</font>");
} else if (style instanceof AbsoluteSizeSpan) {
mOut.append("</font>");
} else if (style instanceof StrikethroughSpan) {
mOut.append("</strike>");
} else if (style instanceof SubscriptSpan) {
mOut.append("</sub>");
} else if (style instanceof SuperscriptSpan) {
mOut.append("</sup>");
} else if (style instanceof UnderlineSpan) {
mOut.append("</u>");
} else if (style instanceof BoldSpan) {
mOut.append("</b>");
} else if (style instanceof ItalicSpan) {
mOut.append("</i>");
}
}
private void handleEndTag(CharacterStyle style) {
if (style instanceof URLSpan) {
mOut.append("</a>");
} else if (style instanceof TypefaceSpan) {
mOut.append("</font>");
} else if (style instanceof ForegroundColorSpan) {
mOut.append("</font>");
} else if (style instanceof BackgroundColorSpan) {
mOut.append("</font>");
} else if (style instanceof AbsoluteSizeSpan) {
mOut.append("</font>");
} else if (style instanceof StrikethroughSpan) {
mOut.append("</strike>");
} else if (style instanceof SubscriptSpan) {
mOut.append("</sub>");
} else if (style instanceof SuperscriptSpan) {
mOut.append("</sup>");
} else if (style instanceof UnderlineSpan) {
mOut.append("</u>");
} else if (style instanceof BoldSpan) {
mOut.append("</b>");
} else if (style instanceof ItalicSpan) {
mOut.append("</i>");
}
}
private static JSONArray extractClass(final SpannableString ss, final Class<? extends CharacterStyle> clz) {
val array = new JSONArray();
val spansBg = ss.getSpans(0, ss.length(), clz);
for (val span : spansBg) {
int col;
switch (clz.getSimpleName()) {
case "BackgroundColorSpan":
col = ((BackgroundColorSpan) span).getBackgroundColor();
break;
case "ForegroundColorSpan":
col = ((ForegroundColorSpan) span).getForegroundColor();
break;
default:
throw new RuntimeException("Cant match extract class type: " + clz.getSimpleName());
}
pullSpanColor(ss, span, col, array);
}
return array;
}
private static JSONArray extractClass(final SpannableString ss, final Class<? extends CharacterStyle> clz) {
val array = new JSONArray();
val spansBg = ss.getSpans(0, ss.length(), clz);
for (val span : spansBg) {
int col;
switch (clz.getSimpleName()) {
case "BackgroundColorSpan":
col = ((BackgroundColorSpan) span).getBackgroundColor();
break;
case "ForegroundColorSpan":
col = ((ForegroundColorSpan) span).getForegroundColor();
break;
default:
throw new RuntimeException("Cant match extract class type: " + clz.getSimpleName());
}
pullSpanColor(ss, span, col, array);
}
return array;
}
private void setBodyText(MessageRecord messageRecord, @Nullable String searchQuery) {
bodyText.setClickable(false);
bodyText.setFocusable(false);
bodyText.setTextSize(TypedValue.COMPLEX_UNIT_SP, TextSecurePreferences.getMessageBodyTextSize(context));
bodyText.setMovementMethod(LongClickMovementMethod.getInstance(getContext()));
if (messageRecord.isRemoteDelete()) {
String deletedMessage = context.getString(R.string.ConversationItem_this_message_was_deleted);
SpannableString italics = new SpannableString(deletedMessage);
italics.setSpan(new RelativeSizeSpan(0.9f), 0, deletedMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
italics.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, deletedMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
bodyText.setText(italics);
} else if (isCaptionlessMms(messageRecord)) {
bodyText.setVisibility(View.GONE);
} else {
Spannable styledText = linkifyMessageBody(messageRecord.getDisplayBody(getContext()), batchSelected.isEmpty());
styledText = SearchUtil.getHighlightedSpan(locale, () -> new BackgroundColorSpan(Color.YELLOW), styledText, searchQuery);
styledText = SearchUtil.getHighlightedSpan(locale, () -> new ForegroundColorSpan(Color.BLACK), styledText, searchQuery);
if (hasExtraText(messageRecord)) {
bodyText.setOverflowText(getLongMessageSpan(messageRecord));
} else {
bodyText.setOverflowText(null);
}
bodyText.setText(styledText);
bodyText.setVisibility(View.VISIBLE);
}
}
@Override
protected void renderHighLightNote() {
int titleIndex = currentNoteInfo.title.indexOf(keyWord);
SpannableStringBuilder hightTitleBuilder = new SpannableStringBuilder(currentNoteInfo.title);
if(titleIndex>-1){
hightTitleBuilder.setSpan(new BackgroundColorSpan(bg_color),titleIndex,titleIndex+keyWord.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
note_detail_groupname.setText(hightTitleBuilder);
note_detail_time.setText(currentNoteInfo.date+" "+currentNoteInfo.time);
String orginContent = currentNoteInfo.content;
Pattern contentP = Pattern.compile(keyWord);
Pattern contentPNCR = Pattern.compile(encode(keyWord));
Matcher contentM = contentP.matcher(orginContent);
Matcher contentMNCR = contentPNCR.matcher(orginContent);
StringBuilder currentNoteDetailFake =new StringBuilder();
int lastIndex = 0;
int MSearchNum = 0;
while( contentM.find()){
currentNoteDetailFake.append(orginContent.substring(lastIndex,contentM.start()));
currentNoteDetailFake.append("<span style=\"background-color:#d4e157\">");
currentNoteDetailFake.append(orginContent.substring(contentM.start(),contentM.end()));
currentNoteDetailFake.append("</span>");
lastIndex =contentM.end();
MSearchNum++;
}
if(MSearchNum == 0){
while( contentMNCR.find()){
currentNoteDetailFake.append(orginContent.substring(lastIndex,contentMNCR.start()));
currentNoteDetailFake.append("<span style=\"background-color:#d4e157\">");
currentNoteDetailFake.append(orginContent.substring(contentMNCR.start(),contentMNCR.end()));
currentNoteDetailFake.append("</span>");
lastIndex =contentMNCR.end();
}
}
currentNoteDetailFake.append(orginContent.substring(lastIndex,orginContent.length()));
contentTV.setHtmlText(currentNoteDetailFake.toString(),false);
}
public SpannableString buildSpannableString() {
SpannableStringBuilder spannableStringBuilder =
new SpannableStringBuilder(captionStringBuilder);
int length = spannableStringBuilder.length();
if (length > 0) {
if (italicsStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new StyleSpan(Typeface.ITALIC), italicsStartPosition,
length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (underlineStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new UnderlineSpan(), underlineStartPosition,
length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (foregroundColorStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new ForegroundColorSpan(foregroundColor),
foregroundColorStartPosition, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (backgroundColorStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new BackgroundColorSpan(backgroundColor),
backgroundColorStartPosition, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return new SpannableString(spannableStringBuilder);
}
public SimpleText background(@ColorRes int colorRes) {
int color = ContextCompat.getColor(context, colorRes);
for (Range range : rangeList) {
setSpan(new BackgroundColorSpan(color), range.from, range.to, SPAN_MODE);
}
return this;
}
public void setPenColor(int foregroundColor, int backgroundColor, int edgeColor) {
if (foregroundColorStartPosition != C.POSITION_UNSET) {
if (this.foregroundColor != foregroundColor) {
captionStringBuilder.setSpan(new ForegroundColorSpan(this.foregroundColor),
foregroundColorStartPosition, captionStringBuilder.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
if (foregroundColor != COLOR_SOLID_WHITE) {
foregroundColorStartPosition = captionStringBuilder.length();
this.foregroundColor = foregroundColor;
}
if (backgroundColorStartPosition != C.POSITION_UNSET) {
if (this.backgroundColor != backgroundColor) {
captionStringBuilder.setSpan(new BackgroundColorSpan(this.backgroundColor),
backgroundColorStartPosition, captionStringBuilder.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
if (backgroundColor != COLOR_SOLID_BLACK) {
backgroundColorStartPosition = captionStringBuilder.length();
this.backgroundColor = backgroundColor;
}
// TODO: Add support for edge color.
}
public SpannableString buildSpannableString() {
SpannableStringBuilder spannableStringBuilder =
new SpannableStringBuilder(captionStringBuilder);
int length = spannableStringBuilder.length();
if (length > 0) {
if (italicsStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new StyleSpan(Typeface.ITALIC), italicsStartPosition,
length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (underlineStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new UnderlineSpan(), underlineStartPosition,
length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (foregroundColorStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new ForegroundColorSpan(foregroundColor),
foregroundColorStartPosition, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (backgroundColorStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new BackgroundColorSpan(backgroundColor),
backgroundColorStartPosition, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return new SpannableString(spannableStringBuilder);
}
@WorkerThread
public void find(String what, boolean matchCase, boolean regex, boolean wordOnly, Editable e) {
Pattern pattern;
if (regex) {
if (matchCase) {
pattern = Pattern.compile(what);
} else {
pattern = Pattern.compile(what,
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
}
} else {
if (wordOnly) {
if (matchCase) {
pattern = Pattern.compile("\\s" + what + "\\s");
} else {
pattern = Pattern.compile("\\s" + Pattern.quote(what) + "\\s",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
}
} else {
if (matchCase) {
pattern = Pattern.compile(Pattern.quote(what));
} else {
pattern = Pattern.compile(Pattern.quote(what),
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
}
}
}
//Очищаем background-спаны, потому что будем накладывать новые
clearSpans(e, false, true, false);
for (Matcher m = pattern.matcher(e); m.find(); ) {
e.setSpan(new BackgroundColorSpan(mColorSearchSpan.data),
m.start(),
m.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
/**
* highlight find word
*
* @param what - input
* @param regex - is java regex
* @param wordOnly - find word only
*/
public void find(String what, boolean regex, boolean wordOnly, boolean matchCase) {
Pattern pattern;
if (regex) {
if (matchCase) {
pattern = Pattern.compile(what);
} else {
pattern = Pattern.compile(what, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
}
} else {
if (wordOnly) {
if (matchCase) {
pattern = Pattern.compile("\\s" + what + "\\s");
} else {
pattern = Pattern.compile("\\s" + Pattern.quote(what) + "\\s", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
}
} else {
if (matchCase) {
pattern = Pattern.compile(Pattern.quote(what));
} else {
pattern = Pattern.compile(Pattern.quote(what), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
}
}
}
Editable e = getEditableText();
//remove all span
BackgroundColorSpan spans[] = e.getSpans(0, e.length(), BackgroundColorSpan.class);
for (int n = spans.length; n-- > 0; )
e.removeSpan(spans[n]);
//set span
for (Matcher m = pattern.matcher(e); m.find(); ) {
e.setSpan(new BackgroundColorSpan(codeTheme.getErrorColor()),
m.start(),
m.end(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
private void setTimedText(final SubtitleTrackEvent textObj) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (textObj == null) {
mSubtitleText.setVisibility(View.INVISIBLE);
return;
}
String text = textObj.getText();
if (text == null || text.length() == 0) {
mSubtitleText.setVisibility(View.INVISIBLE);
return;
}
// Encode whitespace as html entities
text = text.replaceAll("\\r\\n", "<br>");
text = text.replaceAll("\\\\h", " ");
SpannableString span = new SpannableString(TextUtilsKt.toHtmlSpanned(text));
span.setSpan(new ForegroundColorSpan(Color.WHITE), 0, span.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
span.setSpan(new BackgroundColorSpan(ContextCompat.getColor(mActivity, R.color.black_opaque)), 0, span.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mSubtitleText.setText(span);
mSubtitleText.setVisibility(View.VISIBLE);
}
});
}
public void setPenColor(int foregroundColor, int backgroundColor, int edgeColor) {
if (foregroundColorStartPosition != C.POSITION_UNSET) {
if (this.foregroundColor != foregroundColor) {
captionStringBuilder.setSpan(new ForegroundColorSpan(this.foregroundColor),
foregroundColorStartPosition, captionStringBuilder.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
if (foregroundColor != COLOR_SOLID_WHITE) {
foregroundColorStartPosition = captionStringBuilder.length();
this.foregroundColor = foregroundColor;
}
if (backgroundColorStartPosition != C.POSITION_UNSET) {
if (this.backgroundColor != backgroundColor) {
captionStringBuilder.setSpan(new BackgroundColorSpan(this.backgroundColor),
backgroundColorStartPosition, captionStringBuilder.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
if (backgroundColor != COLOR_SOLID_BLACK) {
backgroundColorStartPosition = captionStringBuilder.length();
this.backgroundColor = backgroundColor;
}
// TODO: Add support for edge color.
}
public SpannableString buildSpannableString() {
SpannableStringBuilder spannableStringBuilder =
new SpannableStringBuilder(captionStringBuilder);
int length = spannableStringBuilder.length();
if (length > 0) {
if (italicsStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new StyleSpan(Typeface.ITALIC), italicsStartPosition,
length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (underlineStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new UnderlineSpan(), underlineStartPosition,
length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (foregroundColorStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new ForegroundColorSpan(foregroundColor),
foregroundColorStartPosition, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (backgroundColorStartPosition != C.POSITION_UNSET) {
spannableStringBuilder.setSpan(new BackgroundColorSpan(backgroundColor),
backgroundColorStartPosition, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
return new SpannableString(spannableStringBuilder);
}
/**
* Remove and/or add {@link Spanned.SPAN_EXCLUSIVE_EXCLUSIVE} spans, since they should only exist
* as long as the text they cover is the same. All other spans will remain the same, since they
* will adapt to the new text, hence why {@link SpannableStringBuilder#replace} never removes
* them.
*/
private void manageSpans(SpannableStringBuilder spannableStringBuilder) {
Object[] spans = getText().getSpans(0, length(), Object.class);
for (int spanIdx = 0; spanIdx < spans.length; spanIdx++) {
// Remove all styling spans we might have previously set
if (ForegroundColorSpan.class.isInstance(spans[spanIdx]) ||
BackgroundColorSpan.class.isInstance(spans[spanIdx]) ||
AbsoluteSizeSpan.class.isInstance(spans[spanIdx]) ||
CustomStyleSpan.class.isInstance(spans[spanIdx]) ||
ReactTagSpan.class.isInstance(spans[spanIdx])) {
getText().removeSpan(spans[spanIdx]);
}
if ((getText().getSpanFlags(spans[spanIdx]) & Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) !=
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) {
continue;
}
Object span = spans[spanIdx];
final int spanStart = getText().getSpanStart(spans[spanIdx]);
final int spanEnd = getText().getSpanEnd(spans[spanIdx]);
final int spanFlags = getText().getSpanFlags(spans[spanIdx]);
// Make sure the span is removed from existing text, otherwise the spans we set will be
// ignored or it will cover text that has changed.
getText().removeSpan(spans[spanIdx]);
if (sameTextForSpan(getText(), spannableStringBuilder, spanStart, spanEnd)) {
spannableStringBuilder.setSpan(span, spanStart, spanEnd, spanFlags);
}
}
}