Java Code Examples for android.text.Spannable#setSpan()
The following examples show how to use
android.text.Spannable#setSpan() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SuggestionView.java From delion with Apache License 2.0 | 6 votes |
private boolean applyHighlightToMatchRegions( Spannable str, List<MatchClassification> classifications) { boolean hasMatch = false; for (int i = 0; i < classifications.size(); i++) { MatchClassification classification = classifications.get(i); if ((classification.style & MatchClassificationStyle.MATCH) == MatchClassificationStyle.MATCH) { int matchStartIndex = classification.offset; int matchEndIndex; if (i == classifications.size() - 1) { matchEndIndex = str.length(); } else { matchEndIndex = classifications.get(i + 1).offset; } matchStartIndex = Math.min(matchStartIndex, str.length()); matchEndIndex = Math.min(matchEndIndex, str.length()); hasMatch = true; // Bold the part of the URL that matches the user query. str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), matchStartIndex, matchEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } return hasMatch; }
Example 2
Source File: RichEditText.java From o2oa with GNU Affero General Public License v3.0 | 6 votes |
public static Spannable matchTopic(Spannable spannable) { String text = spannable.toString(); Pattern pattern = Pattern.compile(MATCH_TOPIC); Matcher matcher = pattern.matcher(text); while (matcher.find()) { String str = matcher.group(); int matcherStart = matcher.start(); int matcherEnd = matcher.end(); spannable.setSpan(new TagSpan(str), matcherStart, matcherEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); log("matchTopic:" + str + " " + matcherStart + " " + matcherEnd); } return spannable; }
Example 3
Source File: CensoredTextHolderEx.java From actor-platform with GNU Affero General Public License v3.0 | 6 votes |
@Override public void bindRawText(CharSequence rawText, long readDate, long receiveDate, Spannable reactions, Message message, boolean isItalic) { Spannable res = new SpannableString(rawText); for (String s : badWords) { // rawText = rawText.toString().replaceAll("/*(?i)" + s + "/*", new String(new char[s.length()]).replace('\0', '*')); Pattern p = Pattern.compile("/*(?i)" + s + "/*"); Matcher m = p.matcher(rawText.toString()); while (m.find()) { CensorSpan span = new CensorSpan(); res.setSpan(span, m.start(), m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } super.bindRawText(res, readDate, receiveDate, reactions, message, isItalic); }
Example 4
Source File: CommentsAdapter.java From mentions with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Highlights all the {@link Mentionable}s in the test {@link Comment}. */ private void highlightMentions(final TextView commentTextView, final List<Mentionable> mentions) { if(commentTextView != null && mentions != null && !mentions.isEmpty()) { final Spannable spannable = new SpannableString(commentTextView.getText()); for (Mentionable mention: mentions) { if (mention != null) { final int start = mention.getMentionOffset(); final int end = start + mention.getMentionLength(); if (commentTextView.length() >= end) { spannable.setSpan(new ForegroundColorSpan(orange), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); commentTextView.setText(spannable, TextView.BufferType.SPANNABLE); } else { //Something went wrong. The expected text that we're trying to highlight does not // match the actual text at that position. Log.w("Mentions Sample", "Mention lost. [" + mention + "]"); } } } } }
Example 5
Source File: ParagraphSpanProcessor.java From Android-RTEditor with Apache License 2.0 | 6 votes |
void process(Spannable str) { for (ParagraphSpan paragraphSpan : mParagraphSpans) { RTParagraphSpan<V> span = paragraphSpan.mSpan; int paraStart = paragraphSpan.mParagraph.start(); if (paragraphSpan.mRemove) { int spanStart = str.getSpanStart(span); if (spanStart > -1 && spanStart < paraStart) { // process preceding spans str.setSpan(span.createClone(), spanStart, paraStart, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } str.removeSpan(span); } else { Paragraph paragraph = paragraphSpan.mParagraph; int paraEnd = paragraphSpan.mParagraph.end(); int flags = paragraph.isLast() && paragraph.isEmpty() ? Spanned.SPAN_INCLUSIVE_INCLUSIVE : paragraph.isLast() && paragraph.isFirst() ? Spanned.SPAN_INCLUSIVE_INCLUSIVE : paragraph.isLast() ? Spanned.SPAN_EXCLUSIVE_INCLUSIVE : Spanned.SPAN_EXCLUSIVE_EXCLUSIVE; str.setSpan(span, paraStart, paraEnd, flags); } } }
Example 6
Source File: EmoticonHandler.java From ChatKeyboard-master with BSD 3-Clause "New" or "Revised" License | 6 votes |
public void setTextFace(String content, Spannable spannable, int start, int size) { if (mEmoticonBeans == null) { mEmoticonBeans = emoticonDbHelper.queryAllEmoticonBeans(); emoticonDbHelper.cleanup(); } if (content.length() <= 0) { return; } int keyIndex = start; for (EmoticonBean bean : mEmoticonBeans) { String key = bean.getTag(); int keyLength = key.length(); while (keyIndex >= 0) { keyIndex = content.indexOf(key, keyIndex); //when do not find, get -1 if (keyIndex < 0) { break; } Drawable drawable = EmoticonLoader.getInstance(mContext).getDrawable(bean.getIconUri()); drawable.setBounds(0, 0, size, size); VerticalImageSpan imageSpan = new VerticalImageSpan(drawable); spannable.setSpan(imageSpan, keyIndex, keyIndex + keyLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); keyIndex += keyLength; } keyIndex = start; } }
Example 7
Source File: SuggestionView.java From 365browser with Apache License 2.0 | 6 votes |
private boolean applyHighlightToMatchRegions( Spannable str, List<MatchClassification> classifications) { boolean hasMatch = false; for (int i = 0; i < classifications.size(); i++) { MatchClassification classification = classifications.get(i); if ((classification.style & MatchClassificationStyle.MATCH) == MatchClassificationStyle.MATCH) { int matchStartIndex = classification.offset; int matchEndIndex; if (i == classifications.size() - 1) { matchEndIndex = str.length(); } else { matchEndIndex = classifications.get(i + 1).offset; } matchStartIndex = Math.min(matchStartIndex, str.length()); matchEndIndex = Math.min(matchEndIndex, str.length()); hasMatch = true; // Bold the part of the URL that matches the user query. str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), matchStartIndex, matchEndIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } return hasMatch; }
Example 8
Source File: ListView.java From appinventor-extensions with Apache License 2.0 | 6 votes |
public Spannable[] itemsToColoredText() { // TODO(hal): Generalize this so that different items could have different // colors and even fonts and sizes int size = items.size(); int displayTextSize = textSize; Spannable [] objects = new Spannable[size]; for (int i = 1; i <= size; i++) { // Note that the ListPicker and otherPickers pickers convert Yail lists to string by calling // YailList.ToStringArray. // ListView however, does the string conversion via the adapter, so we must ensure // that the adapter uses YailListElementToSring String itemString = YailList.YailListElementToString(items.get(i)); // Is there a more efficient way to do conversion to spannable strings that does not // need to allocate new objects? Spannable chars = new SpannableString(itemString); chars.setSpan(new ForegroundColorSpan(textColor),0,chars.length(),0); if (!container.$form().getCompatibilityMode()) { displayTextSize = (int) (textSize * container.$form().deviceDensity()); } chars.setSpan(new AbsoluteSizeSpan(displayTextSize),0,chars.length(),0); objects[i - 1] = chars; } return objects; }
Example 9
Source File: LinkMovementMethod2.java From Nimingban with Apache License 2.0 | 5 votes |
@Override public void onTakeFocus(TextView view, Spannable text, int dir) { Selection.removeSelection(text); if ((dir & View.FOCUS_BACKWARD) != 0) { text.setSpan(FROM_BELOW, 0, 0, Spannable.SPAN_POINT_POINT); } else { text.removeSpan(FROM_BELOW); } }
Example 10
Source File: MainActivity.java From SlotMachine with Apache License 2.0 | 5 votes |
private void setSuccessResultMessage(int position) { mResultsText.setVisibility(View.VISIBLE); String resultString = null; int startPos = 0; int endPos = 0; String beverage = null; Resources res = getResources(); if (position == 1) { beverage = res.getString(R.string.beverage_coffee); } else if (position == 2) { beverage = res.getString(R.string.beverage_tea); } else if (position == 3) { beverage = res.getString(R.string.beverage_espresso); } else { mResultsText.setVisibility(View.INVISIBLE); return; } resultString = String.format(res.getString(R.string.result_text), beverage); startPos = resultString.indexOf(beverage, 0); endPos = startPos + beverage.length(); Spannable wordToSpan = new SpannableString(resultString); wordToSpan.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.button_start_color)), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); wordToSpan.setSpan(new RelativeSizeSpan(1.5f), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mResultsText.setText(wordToSpan); }
Example 11
Source File: MessageFormatter.java From talk-android with MIT License | 5 votes |
public static Spannable formatURLSpan(String str) { Spannable s = new SpannableStringBuilder(str); Linkify.addLinks(s, Linkify.WEB_URLS); URLSpan[] urlSpans = s.getSpans(0, s.length(), URLSpan.class); for (URLSpan urlSpan : urlSpans) { int start = s.getSpanStart(urlSpan); int end = s.getSpanEnd(urlSpan); s.removeSpan(urlSpan); s.setSpan(new TalkURLSpan(urlSpan.getURL(), ThemeUtil.getThemeColor(MainApp.CONTEXT. getResources(), BizLogic.getTeamColor())), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return s; }
Example 12
Source File: SuggestionSpanUtils.java From AOSP-Kayboard-7.1.2 with Apache License 2.0 | 5 votes |
@UsedForTesting public static CharSequence getTextWithSuggestionSpan(final Context context, final String pickedWord, final SuggestedWords suggestedWords, final Locale locale) { if (TextUtils.isEmpty(pickedWord) || suggestedWords.isEmpty() || suggestedWords.isPrediction() || suggestedWords.isPunctuationSuggestions()) { return pickedWord; } final ArrayList<String> suggestionsList = new ArrayList<>(); for (int i = 0; i < suggestedWords.size(); ++i) { if (suggestionsList.size() >= SuggestionSpan.SUGGESTIONS_MAX_SIZE) { break; } final SuggestedWordInfo info = suggestedWords.getInfo(i); if (info.isKindOf(SuggestedWordInfo.KIND_PREDICTION)) { continue; } final String word = suggestedWords.getWord(i); if (!TextUtils.equals(pickedWord, word)) { suggestionsList.add(word.toString()); } } final SuggestionSpan suggestionSpan = new SuggestionSpan(context, locale, suggestionsList.toArray(new String[suggestionsList.size()]), 0 /* flags */, null); final Spannable spannable = new SpannableString(pickedWord); spannable.setSpan(suggestionSpan, 0, pickedWord.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return spannable; }
Example 13
Source File: Utils.java From friendly-plans with GNU General Public License v3.0 | 5 votes |
public static void markFieldMandatory(TextView tv) { String text = tv.getText() + ASTERISK; Spannable wordToSpan = new SpannableString(text); wordToSpan.setSpan(new ForegroundColorSpan(Color.RED), text.indexOf('*'), text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); tv.setText(wordToSpan); }
Example 14
Source File: PatternsHelper.java From fanfouapp-opensource with Apache License 2.0 | 5 votes |
public static void removeUnderlines(final TextView textView) { final Spannable s = (Spannable) textView.getText(); final URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class); for (URLSpan span : spans) { final int start = s.getSpanStart(span); final int end = s.getSpanEnd(span); s.removeSpan(span); span = new LinkifyCompat.URLSpanNoUnderline(span.getURL()); s.setSpan(span, start, end, 0); } textView.setText(s); }
Example 15
Source File: QuestionWidget.java From commcare-android with Apache License 2.0 | 5 votes |
private void stripUnderlines(TextView textView) { Spannable s = (Spannable)textView.getText(); URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class); for (URLSpan span : spans) { int start = s.getSpanStart(span); int end = s.getSpanEnd(span); s.removeSpan(span); span = new URLSpanNoUnderline(span.getURL()); s.setSpan(span, start, end, 0); } textView.setText(s); }
Example 16
Source File: LocaleSpanCompatUtils.java From AOSP-Kayboard-7.1.2 with Apache License 2.0 | 4 votes |
private static void removeLocaleSpanFromRange(final Object localeSpan, final Spannable spannable, final int removeStart, final int removeEnd) { if (!isLocaleSpanAvailable()) { return; } final int spanStart = spannable.getSpanStart(localeSpan); final int spanEnd = spannable.getSpanEnd(localeSpan); if (spanStart > spanEnd) { Log.e(TAG, "Invalid span: spanStart=" + spanStart + " spanEnd=" + spanEnd); return; } if (spanEnd < removeStart) { // spanStart < spanEnd < removeStart < removeEnd return; } if (removeEnd < spanStart) { // spanStart < removeEnd < spanStart < spanEnd return; } final int spanFlags = spannable.getSpanFlags(localeSpan); if (spanStart < removeStart) { if (removeEnd < spanEnd) { // spanStart < removeStart < removeEnd < spanEnd final Locale locale = getLocaleFromLocaleSpan(localeSpan); spannable.setSpan(localeSpan, spanStart, removeStart, spanFlags); final Object attionalLocaleSpan = newLocaleSpan(locale); spannable.setSpan(attionalLocaleSpan, removeEnd, spanEnd, spanFlags); return; } // spanStart < removeStart < spanEnd <= removeEnd spannable.setSpan(localeSpan, spanStart, removeStart, spanFlags); return; } if (removeEnd < spanEnd) { // removeStart <= spanStart < removeEnd < spanEnd spannable.setSpan(localeSpan, removeEnd, spanEnd, spanFlags); return; } // removeStart <= spanStart < spanEnd < removeEnd spannable.removeSpan(localeSpan); }
Example 17
Source File: AddressBookResultHandler.java From barcodescanner-lib-aar with MIT License | 4 votes |
@Override public CharSequence getDisplayContents() { AddressBookParsedResult result = (AddressBookParsedResult) getResult(); StringBuilder contents = new StringBuilder(100); ParsedResult.maybeAppend(result.getNames(), contents); int namesLength = contents.length(); String pronunciation = result.getPronunciation(); if (pronunciation != null && !pronunciation.isEmpty()) { contents.append("\n("); contents.append(pronunciation); contents.append(')'); } ParsedResult.maybeAppend(result.getTitle(), contents); ParsedResult.maybeAppend(result.getOrg(), contents); ParsedResult.maybeAppend(result.getAddresses(), contents); String[] numbers = result.getPhoneNumbers(); if (numbers != null) { for (String number : numbers) { if (number != null) { ParsedResult.maybeAppend(PhoneNumberUtils.formatNumber(number), contents); } } } ParsedResult.maybeAppend(result.getEmails(), contents); ParsedResult.maybeAppend(result.getURLs(), contents); String birthday = result.getBirthday(); if (birthday != null && !birthday.isEmpty()) { Date date = parseDate(birthday); if (date != null) { ParsedResult.maybeAppend(DateFormat.getDateInstance(DateFormat.MEDIUM).format(date.getTime()), contents); } } ParsedResult.maybeAppend(result.getNote(), contents); if (namesLength > 0) { // Bold the full name to make it stand out a bit. Spannable styled = new SpannableString(contents.toString()); styled.setSpan(new StyleSpan(Typeface.BOLD), 0, namesLength, 0); return styled; } else { return contents.toString(); } }
Example 18
Source File: AccessibilityNodeInfoUtils.java From talkback with Apache License 2.0 | 4 votes |
/** * Get text from an accessibility-node, including spans passed from new compat library via Bundle. * If span data is invalid, returns text without spans. Each returned ClickableSpanFromBundle * should be recycled by caller, but is probably leaked without consequences. */ // TODO: Replace with AccessibilityNodeInfoCompat.getText() when it provides spans. // TODO: When androidx support library is available, change all node.getText() to use // AccessibilityNodeInfoCompat.getText via this wrapper. public static CharSequence getText(AccessibilityNodeInfoCompat node) { CharSequence nodeText = node.getText(); if (nodeText == null) { return null; } // Require click action id. int actionId = node.getExtras().getInt(SPANS_ACTION_ID_KEY, NO_VALUE); if (actionId == NO_VALUE) { return nodeText; } // Require span start indices. List<Integer> starts = extrasIntList(node, SPANS_START_KEY); if (starts == null || starts.isEmpty()) { return nodeText; } // Get the rest of span data corresponding to each start point. List<Integer> ends = extrasIntList(node, SPANS_END_KEY, starts.size()); List<Integer> flags = extrasIntList(node, SPANS_FLAGS_KEY, starts.size()); List<Integer> ids = extrasIntList(node, SPANS_ID_KEY, starts.size()); if (ends == null || flags == null || ids == null) { return nodeText; } // For each span... collect matching data from bundle, into spannable string. Spannable spannable = new SpannableString(TextUtils.substring(nodeText, 0, nodeText.length())); for (int i = 0; i < starts.size(); i++) { ClickableSpanFromBundle span = new ClickableSpanFromBundle(ids.get(i), node, actionId); int start = starts.get(i); int end = ends.get(i); if (end < start) { logError("getText", "end=%d < start=%d for i=%d", end, start, i); return nodeText; } spannable.setSpan(span, starts.get(i), ends.get(i), flags.get(i)); } return spannable; }
Example 19
Source File: AddressBookResultHandler.java From zxingfragmentlib with Apache License 2.0 | 4 votes |
@Override public CharSequence getDisplayContents() { AddressBookParsedResult result = (AddressBookParsedResult) getResult(); StringBuilder contents = new StringBuilder(100); ParsedResult.maybeAppend(result.getNames(), contents); int namesLength = contents.length(); String pronunciation = result.getPronunciation(); if (pronunciation != null && !pronunciation.isEmpty()) { contents.append("\n("); contents.append(pronunciation); contents.append(')'); } ParsedResult.maybeAppend(result.getTitle(), contents); ParsedResult.maybeAppend(result.getOrg(), contents); ParsedResult.maybeAppend(result.getAddresses(), contents); String[] numbers = result.getPhoneNumbers(); if (numbers != null) { for (String number : numbers) { if (number != null) { ParsedResult.maybeAppend(PhoneNumberUtils.formatNumber(number), contents); } } } ParsedResult.maybeAppend(result.getEmails(), contents); ParsedResult.maybeAppend(result.getURLs(), contents); String birthday = result.getBirthday(); if (birthday != null && !birthday.isEmpty()) { Date date = parseDate(birthday); if (date != null) { ParsedResult.maybeAppend(DateFormat.getDateInstance(DateFormat.MEDIUM).format(date.getTime()), contents); } } ParsedResult.maybeAppend(result.getNote(), contents); if (namesLength > 0) { // Bold the full name to make it stand out a bit. Spannable styled = new SpannableString(contents.toString()); styled.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, namesLength, 0); return styled; } else { return contents.toString(); } }
Example 20
Source File: DialerFilter.java From android_9.0.0_r45 with Apache License 2.0 | 4 votes |
public void setLettersWatcher(TextWatcher watcher) { CharSequence text = mLetters.getText(); Spannable span = (Spannable)text; span.setSpan(watcher, 0, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); }