Java Code Examples for android.text.Spannable#removeSpan()

The following examples show how to use android.text.Spannable#removeSpan() . 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: EaseSmileUtils.java    From monolog-android with MIT License 6 votes vote down vote up
/**
 * replace existing spannable with smiles
 * @param context
 * @param spannable
 * @return
 */
public static boolean addSmiles(Context context, Spannable spannable) {
    boolean hasChanges = false;
    for (Entry<Pattern, Integer> entry : emoticons.entrySet()) {
        Matcher matcher = entry.getKey().matcher(spannable);
        while (matcher.find()) {
            boolean set = true;
            for (ImageSpan span : spannable.getSpans(matcher.start(),
                    matcher.end(), ImageSpan.class))
                if (spannable.getSpanStart(span) >= matcher.start()
                        && spannable.getSpanEnd(span) <= matcher.end())
                    spannable.removeSpan(span);
                else {
                    set = false;
                    break;
                }
            if (set) {
                hasChanges = true;
                spannable.setSpan(new ImageSpan(context, entry.getValue()),
                        matcher.start(), matcher.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }
    return hasChanges;
}
 
Example 2
Source File: IconTextView.java    From bitmask_android with GNU General Public License v3.0 6 votes vote down vote up
private void addImages(Context context, Spannable spannable, int lineHeight, int colour) {
    final Pattern refImg = Pattern.compile(PATTERN);

    final Matcher matcher = refImg.matcher(spannable);
    while (matcher.find()) {
        boolean set = true;
        for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
            if (spannable.getSpanStart(span) >= matcher.start()
                    && spannable.getSpanEnd(span) <= matcher.end()) {
                spannable.removeSpan(span);
            } else {
                set = false;
                break;
            }
        }
        if (set && imageResource != 0) {
            spannable.setSpan(makeImageSpan(context, imageResource, lineHeight, colour),
                    matcher.start(),
                    matcher.end(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            );
        }
    }
}
 
Example 3
Source File: SpannableStringHelper.java    From revolution-irc with GNU General Public License v3.0 6 votes vote down vote up
public static void setAndMergeSpans(Spannable text, Object what, int start, int end, int flags) {
    Object[] spans = text.getSpans(Math.max(start - 1, 0), Math.min(end + 1, 0), what.getClass());
    for (Object span : spans) {
        if (!areSpansEqual(span, what))
            continue;
        int sFlags = text.getSpanFlags(span);
        if ((sFlags & Spanned.SPAN_COMPOSING) != 0)
            continue;

        int sStart = text.getSpanStart(span);
        int sEnd = text.getSpanEnd(span);
        if (sEnd < start || sStart > end)
            continue;
        text.removeSpan(span);
        if (sStart < start)
            start = sStart;
        if (sEnd > end)
            end = sEnd;
    }
    text.setSpan(what, start, end, flags);
}
 
Example 4
Source File: BaseInputConnection.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public static final void removeComposingSpans(Spannable text) {
    text.removeSpan(COMPOSING);
    Object[] sps = text.getSpans(0, text.length(), Object.class);
    if (sps != null) {
        for (int i=sps.length-1; i>=0; i--) {
            Object o = sps[i];
            if ((text.getSpanFlags(o)&Spanned.SPAN_COMPOSING) != 0) {
                text.removeSpan(o);
            }
        }
    }
}
 
Example 5
Source File: AndroidUtilities.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
public static boolean addLinks(Spannable text, int mask) {
    if (text != null && containsUnsupportedCharacters(text.toString()) || mask == 0) {
        return false;
    }
    final URLSpan[] old = text.getSpans(0, text.length(), URLSpan.class);
    for (int i = old.length - 1; i >= 0; i--) {
        text.removeSpan(old[i]);
    }
    final ArrayList<LinkSpec> links = new ArrayList<>();
    if ((mask & Linkify.PHONE_NUMBERS) != 0) {
        Linkify.addLinks(text, Linkify.PHONE_NUMBERS);
    }
    if ((mask & Linkify.WEB_URLS) != 0) {
        gatherLinks(links, text, LinkifyPort.WEB_URL, new String[]{"http://", "https://", "ton://", "tg://"}, sUrlMatchFilter);
    }
    pruneOverlaps(links);
    if (links.size() == 0) {
        return false;
    }
    for (int a = 0, N = links.size(); a < N; a++) {
        LinkSpec link = links.get(a);
        URLSpan[] oldSpans = text.getSpans(link.start, link.end, URLSpan.class);
        if (oldSpans != null && oldSpans.length > 0) {
            for (int b = 0; b < oldSpans.length; b++) {
                text.removeSpan(oldSpans[b]);
            }
        }
        text.setSpan(new URLSpan(link.url), link.start, link.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return true;
}
 
Example 6
Source File: EntityView.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
/**
 * Removes all background color spans from the Spannable
 *
 * @param raw Spannable to remove background colors from
 */
private static void removeSpans(Spannable raw) {
    //Zero out the existing spans
    BackgroundColorSpan[] spans = raw.getSpans(0, raw.length(), BackgroundColorSpan.class);
    for (BackgroundColorSpan span : spans) {
        raw.removeSpan(span);
    }
}
 
Example 7
Source File: Html.java    From tysq-android with GNU General Public License v3.0 5 votes vote down vote up
private static void setSpanFromMark(Spannable text, Object mark, Object... spans) {
    int where = text.getSpanStart(mark);
    text.removeSpan(mark);
    int len = text.length();
    if (where != len) {
        for (Object span : spans) {
            text.setSpan(span, where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}
 
Example 8
Source File: AlertsCreator.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
public static AlertDialog createSupportAlert(BaseFragment fragment) {
    if (fragment == null || fragment.getParentActivity() == null) {
        return null;
    }
    final TextView message = new TextView(fragment.getParentActivity());
    Spannable spanned = new SpannableString(Html.fromHtml(LocaleController.getString("AskAQuestionInfo", R.string.AskAQuestionInfo).replace("\n", "<br>")));
    URLSpan[] spans = spanned.getSpans(0, spanned.length(), URLSpan.class);
    for (int i = 0; i < spans.length; i++) {
        URLSpan span = spans[i];
        int start = spanned.getSpanStart(span);
        int end = spanned.getSpanEnd(span);
        spanned.removeSpan(span);
        span = new URLSpanNoUnderline(span.getURL()) {
            @Override
            public void onClick(View widget) {
                fragment.dismissCurrentDialig();
                super.onClick(widget);
            }
        };
        spanned.setSpan(span, start, end, 0);
    }
    message.setText(spanned);
    message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    message.setLinkTextColor(Theme.getColor(Theme.key_dialogTextLink));
    message.setHighlightColor(Theme.getColor(Theme.key_dialogLinkSelection));
    message.setPadding(AndroidUtilities.dp(23), 0, AndroidUtilities.dp(23), 0);
    message.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy());
    message.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));

    AlertDialog.Builder builder1 = new AlertDialog.Builder(fragment.getParentActivity());
    builder1.setView(message);
    builder1.setTitle(LocaleController.getString("AskAQuestion", R.string.AskAQuestion));
    builder1.setPositiveButton(LocaleController.getString("AskButton", R.string.AskButton), (dialogInterface, i) -> performAskAQuestion(fragment));
    builder1.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
    return builder1.create();
}
 
Example 9
Source File: TextChipsEditView.java    From talk-android with MIT License 5 votes vote down vote up
/**
 * Replace the more chip, if it exists, with all of the recipient chips it had
 * replaced when the RecipientEditTextView gains focus.
 */
public void removeMoreChip() {
    if (mMoreChip != null) {
        Spannable span = getSpannable();
        span.removeSpan(mMoreChip);
        mMoreChip = null;
        // Re-add the spans that were removed.
        if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
            // Recreate each removed span.
            DrawableRecipientChip[] recipients = getSortedRecipients();
            // Start the search for tokens after the last currently visible
            // chip.
            if (recipients == null || recipients.length == 0) {
                return;
            }
            int end = span.getSpanEnd(recipients[recipients.length - 1]);
            Editable editable = getText();
            for (DrawableRecipientChip chip : mRemovedSpans) {
                int chipStart;
                int chipEnd;
                String token;
                // Need to find the location of the chip, again.
                token = (String) chip.getOriginalText();
                // As we find the matching recipient for the remove spans,
                // reduce the size of the string we need to search.
                // That way, if there are duplicates, we always find the correct
                // recipient.
                chipStart = editable.toString().indexOf(token, end);
                end = chipEnd = Math.min(editable.length(), chipStart + token.length());
                // Only set the span if we found a matching token.
                if (chipStart != -1) {
                    editable.setSpan(chip, chipStart, chipEnd,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
            mRemovedSpans.clear();
        }
    }
}
 
Example 10
Source File: ServerApprovalDialogFragment.java    From Intra with Apache License 2.0 5 votes vote down vote up
private View makeNoticeText() {
  final LayoutInflater inflater = requireActivity().getLayoutInflater();
  final View dialogContent = inflater.inflate(R.layout.server_notice_dialog, null);
  TextView serverWebsite = dialogContent.findViewById(R.id.server_website);
  serverWebsite.setText(R.string.server_choice_website_notice);

  // Remove hyperlink.  Its functionality is provided by the dialog's neutral button instead.
  Spannable s = new SpannableString(serverWebsite.getText());
  for (URLSpan span: s.getSpans(0, s.length(), URLSpan.class)) {
    s.removeSpan(span);
  }
  serverWebsite.setText(s);
  return dialogContent;
}
 
Example 11
Source File: LinkMovementMethod.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@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 12
Source File: RecipientEditTextView.java    From ChipsLibrary with Apache License 2.0 4 votes vote down vote up
/**
 * Create the more chip. The more chip is text that replaces any chips that do not fit in the pre-defined available
 * space when the RecipientEditTextView loses focus.
 */
// Visible for testing.
/* package */void createMoreChip()
  {
  if(mNoChips)
    {
    createMoreChipPlainText();
    return;
    }
  if(!mShouldShrink)
    return;
  final ImageSpan[] tempMore=getSpannable().getSpans(0,getText().length(),MoreImageSpan.class);
  if(tempMore.length>0)
    getSpannable().removeSpan(tempMore[0]);
  final DrawableRecipientChip[] recipients=getSortedRecipients();
  if(recipients==null||recipients.length<=CHIP_LIMIT)
    {
    mMoreChip=null;
    return;
    }
  final Spannable spannable=getSpannable();
  final int numRecipients=recipients.length;
  final int overage=numRecipients-CHIP_LIMIT;
  final MoreImageSpan moreSpan=createMoreSpan(overage);
  mRemovedSpans=new ArrayList<DrawableRecipientChip>();
  int totalReplaceStart=0;
  int totalReplaceEnd=0;
  final Editable text=getText();
  for(int i=numRecipients-overage;i<recipients.length;i++)
    {
    mRemovedSpans.add(recipients[i]);
    if(i==numRecipients-overage)
      totalReplaceStart=spannable.getSpanStart(recipients[i]);
    if(i==recipients.length-1)
      totalReplaceEnd=spannable.getSpanEnd(recipients[i]);
    if(mTemporaryRecipients==null||!mTemporaryRecipients.contains(recipients[i]))
      {
      final int spanStart=spannable.getSpanStart(recipients[i]);
      final int spanEnd=spannable.getSpanEnd(recipients[i]);
      recipients[i].setOriginalText(text.toString().substring(spanStart,spanEnd));
      }
    spannable.removeSpan(recipients[i]);
    }
  if(totalReplaceEnd<text.length())
    totalReplaceEnd=text.length();
  final int end=Math.max(totalReplaceStart,totalReplaceEnd);
  final int start=Math.min(totalReplaceStart,totalReplaceEnd);
  final SpannableString chipText=new SpannableString(text.subSequence(start,end));
  chipText.setSpan(moreSpan,0,chipText.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  text.replace(start,end,chipText);
  mMoreChip=moreSpan;
  // If adding the +more chip goes over the limit, resize accordingly.
  if(!isPhoneQuery()&&getLineCount()>mMaxLines)
    setMaxLines(getLineCount());
  }
 
Example 13
Source File: UrlImageGetter.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
@Override
protected void onPostExecute(Drawable result) {
    if (result == null) {
        // TODO 设置默认错误图片?
        return;
    }
    // set the correct bound according to the result from HTTP call
    int w = result.getIntrinsicWidth();
    int h = result.getIntrinsicHeight();
    urlDrawable.setBounds(0, 0, 0 + w, 0 + h);
    L.i("%d X %d", w, h);

    // change the reference of the current drawable to the result
    // from the HTTP call
    urlDrawable.drawable = result;

    // redraw the image by invalidating the container
    // 由于下面重新设置了ImageSpan,所以这里invalidate就不必要了吧
    // urlDrawable.invalidateSelf();
    // UrlImageGetter.this.mTextView.invalidate();

    // TODO 这种方式基本完美解决显示图片问题, blog?
    // 把提取到下面显示的图片在放出来? 然后点击任何图片 进入到 帖子图片浏览界面。。?
    TextView v = UrlImageGetter.this.mTextView;
    Spannable spanText = (Spannable) v.getText();
    @SuppressWarnings("unchecked") ArrayList<String> imgs = (ArrayList<String>) v.getTag(R.id.poste_image_data);
    ImageSpan[] imageSpans = spanText.getSpans(0, spanText.length(), ImageSpan.class);
    for (ImageSpan imgSpan : imageSpans) {
        int start = spanText.getSpanStart(imgSpan);
        int end = spanText.getSpanEnd(imgSpan);
        L.i("%d-%d :%s", start, end, imgSpan.getSource());
        if (src.equals(imgSpan.getSource())) {
            spanText.removeSpan(imgSpan);
            ImageSpan is = new ImageSpan(result, src, ImageSpan.ALIGN_BASELINE);
            spanText.setSpan(is, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (imgs != null && imgs.contains(src)) {
            ImageClickableSpan ics = new ImageClickableSpan(src);
            spanText.setSpan(ics, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

    }
    // For ICS
    // UrlImageGetter.this.container.setMinimumHeight(
    // (UrlImageGetter.this.container.getHeight() + result.getIntrinsicHeight()));
    // UrlImageGetter.this.container.requestLayout();
    // UrlImageGetter.this.container.invalidate();
}
 
Example 14
Source File: Selection.java    From JotaTextEditor with Apache License 2.0 4 votes vote down vote up
/**
 * Remove the selection or cursor, if any, from the text.
 */
public static final void removeSelection(Spannable text) {
    text.removeSpan(SELECTION_START);
    text.removeSpan(SELECTION_END);
}
 
Example 15
Source File: LongClickableLinkMovementMethod.java    From iBeebo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void initialize(TextView widget, Spannable text) {
    Selection.removeSelection(text);
    text.removeSpan(FROM_BELOW);
}
 
Example 16
Source File: LocaleSpanCompatUtils.java    From Indic-Keyboard with Apache License 2.0 4 votes vote down vote up
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: SocialViewHelper.java    From socialview with Apache License 2.0 4 votes vote down vote up
private void recolorize() {
    final CharSequence text = view.getText();
    if (!(text instanceof Spannable)) {
        throw new IllegalStateException("Attached text is not a Spannable," +
            "add TextView.BufferType.SPANNABLE when setting text to this TextView.");
    }
    final Spannable spannable = (Spannable) text;
    for (final Object span : spannable.getSpans(0, text.length(), CharacterStyle.class)) {
        spannable.removeSpan(span);
    }
    if (isHashtagEnabled()) {
        spanAll(spannable, getHashtagPattern(), new Supplier<CharacterStyle>() {
                @Override
                public CharacterStyle get() {
                    return hashtagClickListener != null
                        ? new SocialClickableSpan(hashtagClickListener, hashtagColors, false)
                        : new ForegroundColorSpan(hashtagColors.getDefaultColor());
                }
            }
        );
    }
    if (isMentionEnabled()) {
        spanAll(spannable, getMentionPattern(), new Supplier<CharacterStyle>() {
                @Override
                public CharacterStyle get() {
                    return mentionClickListener != null
                        ? new SocialClickableSpan(mentionClickListener, mentionColors, false)
                        : new ForegroundColorSpan(mentionColors.getDefaultColor());
                }
            }
        );
    }
    if (isHyperlinkEnabled()) {
        spanAll(spannable, getHyperlinkPattern(), new Supplier<CharacterStyle>() {
                @Override
                public CharacterStyle get() {
                    return hyperlinkClickListener != null
                        ? new SocialClickableSpan(hyperlinkClickListener, hyperlinkColors, true)
                        : new SocialURLSpan(text, hyperlinkColors);
                }
            }
        );
    }
}
 
Example 18
Source File: FileEditorActivity.java    From Android-PreferencesManager with Apache License 2.0 4 votes vote down vote up
private void clearSpans(Spannable source) {
    Object[] toRemoveSpans = source.getSpans(0, source.length(), ForegroundColorSpan.class);
    for (Object toRemoveSpan : toRemoveSpans) {
        source.removeSpan(toRemoveSpan);
    }
}
 
Example 19
Source File: MetaKeyKeyListener.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private static void resetLock(Spannable content, Object what) {
    int current = content.getSpanFlags(what);

    if (current == LOCKED)
        content.removeSpan(what);
}
 
Example 20
Source File: MetaKeyKeyListener.java    From android_9.0.0_r45 with Apache License 2.0 2 votes vote down vote up
/**
 * Stop selecting text.  This does not actually collapse the selection;
 * call {@link android.text.Selection#setSelection} too.
 * @hide pending API review
 */
public static void stopSelecting(View view, Spannable content) {
    content.removeSpan(SELECTING);
}