List of usage examples for android.text Spanned SPAN_EXCLUSIVE_EXCLUSIVE
int SPAN_EXCLUSIVE_EXCLUSIVE
To view the source code for android.text Spanned SPAN_EXCLUSIVE_EXCLUSIVE.
Click Source Link
From source file:com.just.agentweb.AgentWebUtils.java
static void show(View parent, CharSequence text, int duration, @ColorInt int textColor, @ColorInt int bgColor, CharSequence actionText, @ColorInt int actionTextColor, View.OnClickListener listener) { SpannableString spannableString = new SpannableString(text); ForegroundColorSpan colorSpan = new ForegroundColorSpan(textColor); spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); snackbarWeakReference = new WeakReference<>(Snackbar.make(parent, spannableString, duration)); Snackbar snackbar = snackbarWeakReference.get(); View view = snackbar.getView(); view.setBackgroundColor(bgColor);// w w w . java 2s .co m if (actionText != null && actionText.length() > 0 && listener != null) { snackbar.setActionTextColor(actionTextColor); snackbar.setAction(actionText, listener); } snackbar.show(); }
From source file:io.realm.realmtasks.list.ItemViewHolder.java
public void setStrikeThroughRatio(float strikeThroughRatio) { final CharSequence text = this.text.getText(); final int textLength = text.length(); int firstLength = (int) (textLength * strikeThroughRatio); if (firstLength > textLength) { firstLength = textLength;/*from www . jav a 2 s .c o m*/ } else if (firstLength == textLength - 1) { firstLength = textLength; } if (firstLength == previousFirstLength) { return; } previousFirstLength = firstLength; final int appendedLength = textLength - firstLength; final SpannableStringBuilder stringBuilder = new SpannableStringBuilder(text, 0, textLength); stringBuilder.clearSpans(); this.text.setPaintFlags(this.text.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); final CharacterStyle firstCharStyle, secondCharStyle; if (completed) { firstCharStyle = new ForegroundColorSpan(cellCompletedColor); secondCharStyle = new StrikethroughSpan(); } else { firstCharStyle = new StrikethroughSpan(); secondCharStyle = new ForegroundColorSpan(cellDefaultColor); } stringBuilder.setSpan(firstCharStyle, 0, firstLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); stringBuilder.setSpan(secondCharStyle, textLength - appendedLength, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); this.text.setText(stringBuilder); }
From source file:io.github.hidroh.materialistic.widget.StoryView.java
private Spannable decorateUpdated() { SpannableStringBuilder sb = new SpannableStringBuilder("*"); sb.setSpan(new AsteriskSpan(getContext()), sb.length() - 1, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return sb;// w w w. j a v a 2s. c o m }
From source file:com.aboveware.sms.contacts.ContactSuggestionsAdapter.java
private CharSequence formatUrl(CharSequence url) { if (mUrlColor == null) { // Lazily get the URL color from the current theme. TypedValue colorValue = new TypedValue(); mContext.getTheme().resolveAttribute(R.attr.textColorSearchUrl, colorValue, true); mUrlColor = mContext.getResources().getColorStateList(colorValue.resourceId); }//from w ww . ja va 2 s .co m SpannableString text = new SpannableString(url); text.setSpan(new TextAppearanceSpan(null, 0, 0, mUrlColor, null), 0, url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return text; }
From source file:com.ruesga.rview.tasks.AsyncTextDiffProcessor.java
private List<DiffView.AbstractModel> processUnifiedDiffs() { final List<DiffView.AbstractModel> model = new ArrayList<>(); addBinaryAdviseIfNeeded(model);//w w w . jav a 2s .c om if (mDiffs == null) { return model; } int lineNumberA = 0; int lineNumberB = 0; final Spannable.Factory spannableFactory = Spannable.Factory.getInstance(); final int noColor = ContextCompat.getColor(mContext, android.R.color.transparent); final int addedBgColor = ContextCompat.getColor(mContext, R.color.diffAddedBackgroundColor); final int addedFgColor = ContextCompat.getColor(mContext, R.color.diffAddedForegroundColor); final int deletedBgColor = ContextCompat.getColor(mContext, R.color.diffDeletedBackgroundColor); final int deletedFgColor = ContextCompat.getColor(mContext, R.color.diffDeletedForegroundColor); boolean noDiffs = mDiffs.length == 1 && mDiffs[0].a == null && mDiffs[0].b == null; int j = 0; for (DiffContentInfo diff : mDiffs) { if (diff.ab != null) { // Unchanged lines int[] p = processUnchangedLines(diff, model, j, lineNumberA, lineNumberB, noColor, noDiffs); lineNumberA = p[0]; lineNumberB = p[1]; } else { if (diff.a != null) { int pos = 0; for (String line : diff.a) { DiffInfoModel m = new DiffInfoModel(); m.a = ++lineNumberA; m.lineNumberA = String.valueOf(m.a); if (diff.editA != null) { Spannable span = spannableFactory.newSpannable(prepareTabs(line)); if (mHighlightIntralineDiffs) { int s2 = 0; for (ArrayList<Integer> intra : diff.editA) { int s1 = s2 + intra.get(0); s2 = s1 + intra.get(1); int l = pos + line.length(); if ((s1 >= pos && s1 <= l) || (s2 >= pos && s2 <= l) || (s1 <= pos && s2 >= l)) { span.setSpan(new BackgroundColorSpan(deletedFgColor), Math.max(pos, s1) - pos, Math.min(l, s2) - pos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } } m.lineA = span; } else { // No intraline data, but it still could differ at start or at end processNoIntralineDataA(diff, m, line, deletedFgColor); } m.colorA = deletedBgColor; m.colorB = noColor; processHighlights(m); model.add(m); pos += line.length() + 1; } } if (diff.b != null) { int pos = 0; for (String line : diff.b) { DiffInfoModel m = new DiffInfoModel(); m.b = ++lineNumberB; m.lineNumberB = String.valueOf(m.b); if (diff.editB != null) { Spannable span = spannableFactory.newSpannable(prepareTabs(line)); if (mHighlightIntralineDiffs) { int s2 = 0; for (ArrayList<Integer> intra : diff.editB) { int s1 = s2 + intra.get(0); s2 = s1 + intra.get(1); int l = pos + line.length(); if ((s1 >= pos && s1 <= l) || (s2 >= pos && s2 <= l) || (s1 <= pos && s2 >= l)) { span.setSpan(new BackgroundColorSpan(addedFgColor), Math.max(pos, s1) - pos, Math.min(l, s2) - pos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } } m.lineB = span; } else { // No intraline data, but it still could differ at start or at end processNoIntralineDataB(diff, m, line, addedFgColor); } m.colorA = addedBgColor; m.colorB = noColor; processHighlights(m); model.add(m); pos += line.length() + 1; } } } j++; } return model; }
From source file:com.android.tv.guide.ProgramItemView.java
public void setValues(TableEntry entry, int selectedGenreId, long fromUtcMillis, long toUtcMillis, String gapTitle) {//from w w w. j a v a2 s. c o m mTableEntry = entry; ViewGroup.LayoutParams layoutParams = getLayoutParams(); layoutParams.width = entry.getWidth(); setLayoutParams(layoutParams); String title = entry.program != null ? entry.program.getTitle() : null; String episode = entry.program != null ? entry.program.getEpisodeDisplayTitle(getContext()) : null; TextAppearanceSpan titleStyle = sGrayedOutProgramTitleStyle; TextAppearanceSpan episodeStyle = sGrayedOutEpisodeTitleStyle; if (entry.getWidth() < sVisibleThreshold) { setText(null); } else { if (entry.isGap()) { title = gapTitle; episode = null; } else if (entry.hasGenre(selectedGenreId)) { titleStyle = sProgramTitleStyle; episodeStyle = sEpisodeTitleStyle; } if (TextUtils.isEmpty(title)) { title = getResources().getString(R.string.program_title_for_no_information); } if (mTableEntry.scheduledRecording != null) { //TODO(dvr): use a proper icon for UI status. title = "" + title; } SpannableStringBuilder description = new SpannableStringBuilder(); description.append(title); if (!TextUtils.isEmpty(episode)) { description.append('\n'); // Add a 'zero-width joiner'/ZWJ in order to ensure we have the same line height for // all lines. This is a non-printing character so it will not change the horizontal // spacing however it will affect the line height. As we ensure the ZWJ has the same // text style as the title it will make sure the line height is consistent. description.append('\u200D'); int middle = description.length(); description.append(episode); description.setSpan(titleStyle, 0, middle, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); description.setSpan(episodeStyle, middle, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else { description.setSpan(titleStyle, 0, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } setText(description); } measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); mTextWidth = getMeasuredWidth() - getPaddingStart() - getPaddingEnd(); int start = GuideUtils.convertMillisToPixel(entry.entryStartUtcMillis); int guideStart = GuideUtils.convertMillisToPixel(fromUtcMillis); layoutVisibleArea(guideStart - start); // Maximum width for us to use a ripple mMaxWidthForRipple = GuideUtils.convertMillisToPixel(fromUtcMillis, toUtcMillis); }
From source file:org.tlhInganHol.android.klingonassistant.EntryActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TTS:// w w w .j av a2 s . c o m // Initialize text-to-speech. This is an asynchronous operation. // The OnInitListener (second argument) is called after initialization completes. // Log.d(TAG, "Initialising TTS"); mTts = new TextToSpeech(this, this, // TextToSpeech.OnInitListener "org.tlhInganHol.android.klingonttsengine"); // Requires API 14. setDrawerContentView(R.layout.entry); Resources resources = getResources(); JellyBeanSpanFixTextView entryTitle = (JellyBeanSpanFixTextView) findViewById(R.id.entry_title); JellyBeanSpanFixTextView entryText = (JellyBeanSpanFixTextView) findViewById(R.id.definition); // TODO: Save and restore bundle state to preserve links. Uri uri = getIntent().getData(); // Log.d(TAG, "EntryActivity - uri: " + uri.toString()); // TODO: Disable the "About" menu item if this is the "About" entry. mParentQuery = getIntent().getStringExtra(SearchManager.QUERY); // Retrieve the entry's data. // Note: managedQuery is deprecated since API 11. Cursor cursor = managedQuery(uri, KlingonContentDatabase.ALL_KEYS, null, null, null); KlingonContentProvider.Entry entry = new KlingonContentProvider.Entry(cursor, getBaseContext()); // Handle alternative spellings here. if (entry.isAlternativeSpelling()) { // TODO: Immediate redirect to query in entry.getDefinition(); } // Get the shared preferences. SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); // Set the entry's name (along with info like "slang", formatted in HTML). entryTitle.invalidate(); boolean useKlingonFont = sharedPrefs.getBoolean(Preferences.KEY_KLINGON_FONT_CHECKBOX_PREFERENCE, /* default */false); Typeface klingonTypeface = KlingonAssistant.getKlingonFontTypeface(getBaseContext()); if (useKlingonFont) { // Preference is set to display this in {pIqaD}! entryTitle.setTypeface(klingonTypeface); entryTitle.setText(entry.getEntryNameInKlingonFont()); } else { // Boring transcription based on English (Latin) alphabet. entryTitle.setText(Html.fromHtml(entry.getFormattedEntryName(/* isHtml */true))); } mEntryName = entry.getEntryName(); // Set the colour for the entry name depending on its part of speech. boolean useColours = sharedPrefs.getBoolean(Preferences.KEY_USE_COLOURS_CHECKBOX_PREFERENCE, /* default */true); if (useColours) { entryTitle.setTextColor(entry.getTextColor()); } // Create the expanded definition. String pos = entry.getFormattedPartOfSpeech(/* isHtml */false); String expandedDefinition = pos + entry.getDefinition(); // Show the German definition. String definition_DE = ""; boolean displayGermanEntry = entry.shouldDisplayGerman(); int germanDefinitionStart = -1; String germanDefinitionHeader = "\n" + resources.getString(R.string.label_german) + ": "; if (displayGermanEntry) { germanDefinitionStart = expandedDefinition.length(); definition_DE = entry.getDefinition_DE(); expandedDefinition += germanDefinitionHeader + definition_DE; } // Set the share intent. setShareEntryIntent(entry); // Show the basic notes. String notes = entry.getNotes(); if (!notes.equals("")) { expandedDefinition += "\n\n" + notes; } // If this entry is hypothetical or extended canon, display warnings. if (entry.isHypothetical() || entry.isExtendedCanon()) { expandedDefinition += "\n\n"; if (entry.isHypothetical()) { expandedDefinition += resources.getString(R.string.warning_hypothetical); } if (entry.isExtendedCanon()) { expandedDefinition += resources.getString(R.string.warning_extended_canon); } } // Show synonyms, antonyms, and related entries. String synonyms = entry.getSynonyms(); String antonyms = entry.getAntonyms(); String seeAlso = entry.getSeeAlso(); if (!synonyms.equals("")) { expandedDefinition += "\n\n" + resources.getString(R.string.label_synonyms) + ": " + synonyms; } if (!antonyms.equals("")) { expandedDefinition += "\n\n" + resources.getString(R.string.label_antonyms) + ": " + antonyms; } if (!seeAlso.equals("")) { expandedDefinition += "\n\n" + resources.getString(R.string.label_see_also) + ": " + seeAlso; } // Display components if that field is not empty, unless we are showing an analysis link, in // which case we want to hide the components. boolean showAnalysis = entry.isSentence() || entry.isDerivative(); String components = entry.getComponents(); if (!components.equals("")) { // Treat the components column of inherent plurals and their // singulars differently than for other entries. if (entry.isInherentPlural()) { expandedDefinition += "\n\n" + String.format(resources.getString(R.string.info_inherent_plural), components); } else if (entry.isSingularFormOfInherentPlural()) { expandedDefinition += "\n\n" + String.format(resources.getString(R.string.info_singular_form), components); } else if (!showAnalysis) { // This is just a regular list of components. expandedDefinition += "\n\n" + resources.getString(R.string.label_components) + ": " + components; } } // Display plural information. if (!entry.isPlural() && !entry.isInherentPlural() && !entry.isPlural()) { if (entry.isBeingCapableOfLanguage()) { expandedDefinition += "\n\n" + resources.getString(R.string.info_being); } else if (entry.isBodyPart()) { expandedDefinition += "\n\n" + resources.getString(R.string.info_body); } } // If the entry is a useful phrase, link back to its category. if (entry.isSentence()) { String sentenceType = entry.getSentenceType(); if (!sentenceType.equals("")) { // Put the query as a placeholder for the actual category. expandedDefinition += "\n\n" + resources.getString(R.string.label_category) + ": {" + entry.getSentenceTypeQuery() + "}"; } } // If the entry is a sentence, make a link to analyse its components. if (showAnalysis) { String analysisQuery = entry.getEntryName(); if (!components.equals("")) { // Strip the brackets around each component so they won't be processed. analysisQuery += ":" + entry.getPartOfSpeech(); int homophoneNumber = entry.getHomophoneNumber(); if (homophoneNumber != -1) { analysisQuery += ":" + homophoneNumber; } analysisQuery += KlingonContentProvider.Entry.COMPONENTS_MARKER + components.replaceAll("[{}]", ""); } expandedDefinition += "\n\n" + resources.getString(R.string.label_analyze) + ": {" + analysisQuery + "}"; } // Show the examples. String examples = entry.getExamples(); if (!examples.equals("")) { expandedDefinition += "\n\n" + resources.getString(R.string.label_examples) + ": " + examples; } // Show the source. String source = entry.getSource(); if (!source.equals("")) { expandedDefinition += "\n\n" + resources.getString(R.string.label_sources) + ": " + source; } // If this is a verb (but not a prefix or suffix), show the transitivity information. String transitivity = ""; if (entry.isVerb() && sharedPrefs.getBoolean(Preferences.KEY_SHOW_TRANSITIVITY_CHECKBOX_PREFERENCE, /* default */ true)) { // This is a verb and show transitivity preference is set to true. transitivity = entry.getTransitivityString(); } int transitivityStart = -1; String transitivityHeader = "\n\n" + resources.getString(R.string.label_transitivity) + ": "; boolean showTransitivityInformation = !transitivity.equals(""); if (showTransitivityInformation) { transitivityStart = expandedDefinition.length(); expandedDefinition += transitivityHeader + transitivity; } // Show the hidden notes. String hiddenNotes = ""; if (sharedPrefs.getBoolean(Preferences.KEY_SHOW_ADDITIONAL_INFORMATION_CHECKBOX_PREFERENCE, /* default */ true)) { // Show additional information preference set to true. hiddenNotes = entry.getHiddenNotes(); } int hiddenNotesStart = -1; String hiddenNotesHeader = "\n\n" + resources.getString(R.string.label_additional_information) + ": "; if (!hiddenNotes.equals("")) { hiddenNotesStart = expandedDefinition.length(); expandedDefinition += hiddenNotesHeader + hiddenNotes; } // Format the expanded definition, including linkifying the links to other entries. float smallTextScale = (float) 0.8; SpannableStringBuilder ssb = new SpannableStringBuilder(expandedDefinition); int intermediateFlags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_INTERMEDIATE; int finalFlags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE; if (!pos.equals("")) { // Italicise the part of speech. ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, pos.length(), finalFlags); } if (displayGermanEntry) { // Reduce the size of the German definition. ssb.setSpan(new RelativeSizeSpan(smallTextScale), germanDefinitionStart, germanDefinitionStart + germanDefinitionHeader.length() + definition_DE.length(), finalFlags); } if (showTransitivityInformation) { // Reduce the size of the transitivity information. ssb.setSpan(new RelativeSizeSpan(smallTextScale), transitivityStart, transitivityStart + transitivityHeader.length() + transitivity.length(), finalFlags); } if (!hiddenNotes.equals("")) { // Reduce the size of the hidden notes. ssb.setSpan(new RelativeSizeSpan(smallTextScale), hiddenNotesStart, hiddenNotesStart + hiddenNotesHeader.length() + hiddenNotes.length(), finalFlags); } Matcher m = KlingonContentProvider.Entry.ENTRY_PATTERN.matcher(expandedDefinition); while (m.find()) { // Strip the brackets {} to get the query. String query = expandedDefinition.substring(m.start() + 1, m.end() - 1); LookupClickableSpan viewLauncher = new LookupClickableSpan(query); // Process the linked entry information. KlingonContentProvider.Entry linkedEntry = new KlingonContentProvider.Entry(query, getBaseContext()); // Log.d(TAG, "linkedEntry.getEntryName() = " + linkedEntry.getEntryName()); // Delete the brackets and metadata parts of the string (which includes analysis components). ssb.delete(m.start() + 1 + linkedEntry.getEntryName().length(), m.end()); ssb.delete(m.start(), m.start() + 1); int end = m.start() + linkedEntry.getEntryName().length(); // Insert link to the category for a useful phrase. if (entry.isSentence() && !entry.getSentenceType().equals("") && linkedEntry.getEntryName().equals("*")) { // Delete the "*" placeholder. ssb.delete(m.start(), m.start() + 1); // Insert the category name. ssb.insert(m.start(), entry.getSentenceType()); end += entry.getSentenceType().length() - 1; } // Set the font and link. // TODO: Source should link to description of the source. // This is true if this entry doesn't launch an EntryActivity. boolean disableEntryLink = linkedEntry.doNotLink() || linkedEntry.isSource() || linkedEntry.isURL(); // The last span set on a range must have finalFlags. int maybeFinalFlags = disableEntryLink ? finalFlags : intermediateFlags; if (linkedEntry.isSource()) { // Names of sources are in italics. ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), m.start(), end, maybeFinalFlags); } else if (linkedEntry.isURL()) { // Linkify URL if there is one. String url = linkedEntry.getURL(); if (!url.equals("")) { ssb.setSpan(new URLSpan(url), m.start(), end, maybeFinalFlags); } } else if (useKlingonFont) { // Display the text using the Klingon font. Categories (which have an entry of "*") must // be handled specially. String klingonEntryName = !linkedEntry.getEntryName().equals("*") ? linkedEntry.getEntryNameInKlingonFont() : KlingonContentProvider.convertStringToKlingonFont(entry.getSentenceType()); ssb.delete(m.start(), end); ssb.insert(m.start(), klingonEntryName); end = m.start() + klingonEntryName.length(); ssb.setSpan(new KlingonTypefaceSpan("", klingonTypeface), m.start(), end, maybeFinalFlags); } else { // Klingon is in bold serif. ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), m.start(), end, intermediateFlags); ssb.setSpan(new TypefaceSpan("serif"), m.start(), end, maybeFinalFlags); } // If linked entry is hypothetical or extended canon, insert a "?" in front. if (linkedEntry.isHypothetical() || linkedEntry.isExtendedCanon()) { ssb.insert(m.start(), "?"); ssb.setSpan(new RelativeSizeSpan(smallTextScale), m.start(), m.start() + 1, intermediateFlags); ssb.setSpan(new SuperscriptSpan(), m.start(), m.start() + 1, maybeFinalFlags); end++; } // Only apply colours to verbs, nouns, and affixes (exclude BLUE and WHITE). if (!disableEntryLink) { // Link to view launcher. ssb.setSpan(viewLauncher, m.start(), end, useColours ? intermediateFlags : finalFlags); } // Set the colour last, so it's not overridden by other spans. if (useColours) { ssb.setSpan(new ForegroundColorSpan(linkedEntry.getTextColor()), m.start(), end, finalFlags); } String linkedPos = linkedEntry.getBracketedPartOfSpeech(/* isHtml */false); if (!linkedPos.equals("") && linkedPos.length() > 1) { ssb.insert(end, linkedPos); int rightBracketLoc = linkedPos.indexOf(")"); if (rightBracketLoc != -1) { // linkedPos is always of the form " (pos)[ (def'n N)]", we want to italicise // the "pos" part only. ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), end + 2, end + rightBracketLoc, finalFlags); } } // Rinse and repeat. expandedDefinition = ssb.toString(); m = KlingonContentProvider.Entry.ENTRY_PATTERN.matcher(expandedDefinition); } // Display the entry name and definition. entryText.invalidate(); entryText.setText(ssb); entryText.setMovementMethod(LinkMovementMethod.getInstance()); }
From source file:com.juick.android.TagsFragment.java
private void onTagClick(String tagg, int uid) { if (!multi) { parentActivity.onTagClick(tagg, uid); } else {/*from ww w. j a v a 2 s.c o m*/ TextView tv = (TextView) myView.findViewById(R.id.tags); Spannable text = (Spannable) tv.getText(); TagOffsets tagOffsets1 = tagOffsets.get(tagg); if (!selectedTags.remove(tagg)) { if (selectedTags.size() == 5) { Toast.makeText(getActivity(), getString(R.string.TooManyTags), Toast.LENGTH_LONG).show(); return; } else { selectedTags.add(tagg); tagOffsets1.existingSpan = new StyleSpan(Typeface.BOLD); text.setSpan(tagOffsets1.existingSpan, tagOffsets1.offset, tagOffsets1.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } else { text.removeSpan(tagOffsets1.existingSpan); tagOffsets1.existingSpan = null; } final TextView selected = (TextView) myView.findViewById(R.id.selected); StringBuilder sb = new StringBuilder(); for (String selectedTag : selectedTags) { sb.append("*"); sb.append(selectedTag); sb.append(" "); } selected.setText(sb.toString().trim()); } }
From source file:org.mozilla.focus.widget.InlineAutocompleteEditText.java
/** * Add autocomplete text based on the result URI. * * @param result Result URI to be turned into autocomplete text *///from w ww . j a va 2 s .c o m public final void onAutocomplete(final String result) { // If mDiscardAutoCompleteResult is true, we temporarily disabled // autocomplete (due to backspacing, etc.) and we should bail early. if (mDiscardAutoCompleteResult) { return; } if (!isEnabled() || result == null) { mAutoCompleteResult = ""; return; } final Editable text = getText(); final int textLength = text.length(); final int resultLength = result.length(); final int autoCompleteStart = text.getSpanStart(AUTOCOMPLETE_SPAN); mAutoCompleteResult = result; if (autoCompleteStart > -1) { // Autocomplete text already exists; we should replace existing autocomplete text. // If the result and the current text don't have the same prefixes, // the result is stale and we should wait for the another result to come in. if (!TextUtils.regionMatches(result, 0, text, 0, autoCompleteStart)) { return; } beginSettingAutocomplete(); // Replace the existing autocomplete text with new one. // replace() preserves the autocomplete spans that we set before. text.replace(autoCompleteStart, textLength, result, autoCompleteStart, resultLength); // Reshow the cursor if there is no longer any autocomplete text. if (autoCompleteStart == resultLength) { setCursorVisible(true); } endSettingAutocomplete(); } else { // No autocomplete text yet; we should add autocomplete text // If the result prefix doesn't match the current text, // the result is stale and we should wait for the another result to come in. if (resultLength <= textLength || !TextUtils.regionMatches(result, 0, text, 0, textLength)) { return; } final Object[] spans = text.getSpans(textLength, textLength, Object.class); final int[] spanStarts = new int[spans.length]; final int[] spanEnds = new int[spans.length]; final int[] spanFlags = new int[spans.length]; // Save selection/composing span bounds so we can restore them later. for (int i = 0; i < spans.length; i++) { final Object span = spans[i]; final int spanFlag = text.getSpanFlags(span); // We don't care about spans that are not selection or composing spans. // For those spans, spanFlag[i] will be 0 and we don't restore them. if ((spanFlag & Spanned.SPAN_COMPOSING) == 0 && (span != Selection.SELECTION_START) && (span != Selection.SELECTION_END)) { continue; } spanStarts[i] = text.getSpanStart(span); spanEnds[i] = text.getSpanEnd(span); spanFlags[i] = spanFlag; } beginSettingAutocomplete(); // First add trailing text. text.append(result, textLength, resultLength); // Restore selection/composing spans. for (int i = 0; i < spans.length; i++) { final int spanFlag = spanFlags[i]; if (spanFlag == 0) { // Skip if the span was ignored before. continue; } text.setSpan(spans[i], spanStarts[i], spanEnds[i], spanFlag); } // Mark added text as autocomplete text. for (final Object span : mAutoCompleteSpans) { text.setSpan(span, textLength, resultLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } // Hide the cursor. setCursorVisible(false); // Make sure the autocomplete text is visible. If the autocomplete text is too // long, it would appear the cursor will be scrolled out of view. However, this // is not the case in practice, because EditText still makes sure the cursor is // still in view. bringPointIntoView(resultLength); endSettingAutocomplete(); } announceForAccessibility(text.toString()); }
From source file:com.nextgis.maplibui.util.ControlHelper.java
public static void highlightText(TextView textView) { final CharSequence text = textView.getText(); final SpannableString spannableString = new SpannableString(text); spannableString.setSpan(new URLSpan(""), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannableString, TextView.BufferType.SPANNABLE); }