Example usage for android.text SpannableStringBuilder removeSpan

List of usage examples for android.text SpannableStringBuilder removeSpan

Introduction

In this page you can find the example usage for android.text SpannableStringBuilder removeSpan.

Prototype

public void removeSpan(Object what) 

Source Link

Document

Remove the specified markup object from the buffer.

Usage

From source file:com.nttec.everychan.ui.presentation.HtmlParser.java

private static void endAibspoiler(SpannableStringBuilder text, ThemeColors colors, boolean openSpoilers) {
    int len = text.length();
    Object obj = getLast(text, Aibspoiler.class);
    int where = text.getSpanStart(obj);
    text.removeSpan(obj);

    if (where != len && colors != null) {
        if (openSpoilers) {
            text.setSpan(new ForegroundColorSpan(colors.spoilerForeground), where, len,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            text.setSpan(new BackgroundColorSpan(colors.spoilerBackground), where, len,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {/*  www. j a va 2s .  c om*/
            text.setSpan(new SpoilerSpan(colors.spoilerForeground, colors.spoilerBackground), where, len,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}

From source file:com.keylesspalace.tusky.util.LinkHelper.java

/**
 * Finds links, mentions, and hashtags in a piece of text and makes them clickable, associating
 * them with callbacks to notify when they're clicked.
 *
 * @param view the returned text will be put in
 * @param content containing text with mentions, links, or hashtags
 * @param mentions any '@' mentions which are known to be in the content
 * @param listener to notify about particular spans that are clicked
 *//*from   www  .j  a v  a2  s.co  m*/
public static void setClickableText(TextView view, Spanned content, @Nullable Status.Mention[] mentions,
        final LinkListener listener) {

    SpannableStringBuilder builder = new SpannableStringBuilder(content);
    URLSpan[] urlSpans = content.getSpans(0, content.length(), URLSpan.class);
    for (URLSpan span : urlSpans) {
        int start = builder.getSpanStart(span);
        int end = builder.getSpanEnd(span);
        int flags = builder.getSpanFlags(span);
        CharSequence text = builder.subSequence(start, end);
        if (text.charAt(0) == '#') {
            final String tag = text.subSequence(1, text.length()).toString();
            ClickableSpan newSpan = new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    listener.onViewTag(tag);
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false);
                }
            };
            builder.removeSpan(span);
            builder.setSpan(newSpan, start, end, flags);
        } else if (text.charAt(0) == '@' && mentions != null && mentions.length > 0) {
            String accountUsername = text.subSequence(1, text.length()).toString();
            /* There may be multiple matches for users on different instances with the same
             * username. If a match has the same domain we know it's for sure the same, but if
             * that can't be found then just go with whichever one matched last. */
            String id = null;
            for (Status.Mention mention : mentions) {
                if (mention.localUsername.equalsIgnoreCase(accountUsername)) {
                    id = mention.id;
                    if (mention.url.contains(getDomain(span.getURL()))) {
                        break;
                    }
                }
            }
            if (id != null) {
                final String accountId = id;
                ClickableSpan newSpan = new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        listener.onViewAccount(accountId);
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setUnderlineText(false);
                    }
                };
                builder.removeSpan(span);
                builder.setSpan(newSpan, start, end, flags);
            }
        } else {
            ClickableSpan newSpan = new CustomURLSpan(span.getURL());
            builder.removeSpan(span);
            builder.setSpan(newSpan, start, end, flags);
        }
    }
    view.setText(builder);
    view.setLinksClickable(true);
    view.setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:com.nttec.everychan.ui.presentation.HtmlParser.java

private static void endSpan(SpannableStringBuilder text, ThemeColors colors, boolean openSpoilers) {
    int len = text.length();
    Object obj = getLast(text, Span.class);
    int where = text.getSpanStart(obj);
    text.removeSpan(obj);

    if (where != len) {
        Span s = (Span) obj;/*  ww w . j  a va 2 s. c om*/

        if (s.mStyle != null) {
            List<Object> styleSpans = parseStyleAttributes(s.mStyle);
            for (Object span : styleSpans) {
                text.setSpan(span, where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        if (colors != null && s.mIsAibquote) {
            text.setSpan(new ForegroundColorSpan(colors.quoteForeground), where, len,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        if (colors != null && s.mIsAibspoiler) {
            if (openSpoilers) {
                text.setSpan(new ForegroundColorSpan(colors.spoilerForeground), where, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                text.setSpan(new BackgroundColorSpan(colors.spoilerBackground), where, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                text.setSpan(new SpoilerSpan(colors.spoilerForeground, colors.spoilerBackground), where, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        if (s.mIsUnderline) {
            text.setSpan(new UnderlineSpan(), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        if (s.mIsStrike) {
            text.setSpan(new StrikethroughSpan(), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

    }
}

From source file:com.nttec.everychan.ui.presentation.HtmlParser.java

/**
 * ? ? SpoilerSpan  ForegroundColorSpan  ?? ?   ??  ?
 *//* w  ww. ja va 2s . co  m*/
private static void fixSpoilerSpans(SpannableStringBuilder builder, ThemeColors themeColors) {
    SpoilerSpan[] spoilers = builder.getSpans(0, builder.length(), SpoilerSpan.class);
    for (SpoilerSpan span : spoilers) {
        int start = builder.getSpanStart(span);
        int end = builder.getSpanEnd(span);
        builder.removeSpan(span);
        builder.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    ClickableURLSpan[] urls = builder.getSpans(0, builder.length(), ClickableURLSpan.class);
    for (ClickableURLSpan span : urls) {
        int start = builder.getSpanStart(span);
        int end = builder.getSpanEnd(span);
        builder.setSpan(new ForegroundColorSpan(themeColors.urlLinkForeground), start, end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}

From source file:com.android.tv.dvr.ui.DvrUiHelper.java

@NonNull
public static CharSequence getStyledTitleWithEpisodeNumber(Context context, String title, String seasonNumber,
        String episodeNumber, int episodeNumberStyleResId) {
    if (TextUtils.isEmpty(title)) {
        return "";
    }/*from   w  ww  . j a  v a2s.c o m*/
    SpannableStringBuilder builder;
    if (TextUtils.isEmpty(seasonNumber) || seasonNumber.equals("0")) {
        builder = TextUtils.isEmpty(episodeNumber) ? new SpannableStringBuilder(title)
                : new SpannableStringBuilder(Html.fromHtml(context.getString(
                        R.string.program_title_with_episode_number_no_season, title, episodeNumber)));
    } else {
        builder = new SpannableStringBuilder(Html.fromHtml(context
                .getString(R.string.program_title_with_episode_number, title, seasonNumber, episodeNumber)));
    }
    Object[] spans = builder.getSpans(0, builder.length(), Object.class);
    if (spans.length > 0) {
        if (episodeNumberStyleResId != 0) {
            builder.setSpan(new TextAppearanceSpan(context, episodeNumberStyleResId),
                    builder.getSpanStart(spans[0]), builder.getSpanEnd(spans[0]),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        builder.removeSpan(spans[0]);
    }
    return new SpannableString(builder);
}

From source file:pct.droid.fragments.VideoPlayerFragment.java

@Override
protected void showTimedCaptionText(final Caption text) {
    mDisplayHandler.post(new Runnable() {
        @Override/*  w  w  w.j  a va  2 s.  co  m*/
        public void run() {
            if (text == null) {
                if (mSubtitleText.getText().length() > 0) {
                    mSubtitleText.setText("");
                }
                return;
            }
            SpannableStringBuilder styledString = (SpannableStringBuilder) Html.fromHtml(text.content);

            ForegroundColorSpan[] toRemoveSpans = styledString.getSpans(0, styledString.length(),
                    ForegroundColorSpan.class);
            for (ForegroundColorSpan remove : toRemoveSpans) {
                styledString.removeSpan(remove);
            }

            if (!mSubtitleText.getText().toString().equals(styledString.toString())) {
                mSubtitleText.setText(styledString);
            }
        }
    });
}

From source file:com.android.mail.browse.ConversationItemView.java

private void layoutParticipantText(SpannableStringBuilder participantText) {
    if (participantText != null) {
        if (isActivated() && showActivatedText()) {
            participantText.setSpan(sActivatedTextSpan, 0, mHeader.styledMessageInfoStringOffset,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {//w ww. java2s.c om
            participantText.removeSpan(sActivatedTextSpan);
        }

        final int w = mSendersWidth;
        final int h = mCoordinates.sendersHeight;
        mSendersTextView.setLayoutParams(new ViewGroup.LayoutParams(w, h));
        mSendersTextView.setMaxLines(mCoordinates.sendersLineCount);
        mSendersTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mCoordinates.sendersFontSize);
        layoutViewExactly(mSendersTextView, w, h);

        mSendersTextView.setText(participantText);
    }
}

From source file:com.tct.mail.browse.ConversationItemView.java

private void layoutParticipantText(SpannableStringBuilder participantText) {
    if (participantText != null) {
        if (isActivated() && showActivatedText()) {
            participantText.setSpan(sActivatedTextSpan, 0, mHeader.styledMessageInfoStringOffset,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {//from w ww  .  jav a  2 s. c  om
            participantText.removeSpan(sActivatedTextSpan);
        }

        //TS: yanhua.chen 2015-9-2 EMAIL CR_540046 MOD_S
        //Note sender width should use define in xml
        final int w = mCoordinates.sendersWidth;
        //TS: yanhua.chen 2015-9-2 EMAIL CR_540046 MOD_E
        final int h = mCoordinates.sendersHeight;
        mSendersTextView.setLayoutParams(new ViewGroup.LayoutParams(w, h));
        mSendersTextView.setMaxLines(mCoordinates.sendersLineCount);
        mSendersTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mCoordinates.sendersFontSize);
        layoutViewExactly(mSendersTextView, w, h);

        /// TCT: add for search term highlight @{
        boolean hasFilter = (mSearchParams != null && !TextUtils.isEmpty(mSearchParams.mFilter));
        boolean fieldMatched = (mSearchParams != null
                && (SearchParams.SEARCH_FIELD_FROM.equals(mSearchParams.mField)
                        || SearchParams.SEARCH_FIELD_ALL.equals(mSearchParams.mField)
                        || SearchParams.SEARCH_FIELD_TO.equals(mSearchParams.mField))); //porting from PR937141
        if (hasFilter && fieldMatched) {
            CharacterStyle[] spans = participantText.getSpans(0, participantText.length(),
                    CharacterStyle.class);
            String senderToHightlight = participantText.toString();
            CharSequence highlightedSender = TextUtilities.highlightTermsInText(senderToHightlight,
                    mSearchParams.mFilter);
            highlightedSender = copyStyles(spans, highlightedSender);
            mSendersTextView.setText(highlightedSender);
        } else {
            mSendersTextView.setText(participantText);
        }
        /// @}
    }
}

From source file:org.telegram.ui.Components.ChatActivityEnterView.java

public void setEditingMessageObject(MessageObject messageObject, boolean caption) {
    if (audioToSend != null || editingMessageObject == messageObject) {
        return;/*from   w w  w. java  2  s .c o m*/
    }
    if (editingMessageReqId != 0) {
        ConnectionsManager.getInstance().cancelRequest(editingMessageReqId, true);
        editingMessageReqId = 0;
    }
    editingMessageObject = messageObject;
    editingCaption = caption;
    if (editingMessageObject != null) {
        if (doneButtonAnimation != null) {
            doneButtonAnimation.cancel();
            doneButtonAnimation = null;
        }
        doneButtonContainer.setVisibility(View.VISIBLE);
        showEditDoneProgress(true, false);

        InputFilter[] inputFilters = new InputFilter[1];
        if (caption) {
            inputFilters[0] = new InputFilter.LengthFilter(200);
            if (editingMessageObject.caption != null) {
                setFieldText(Emoji.replaceEmoji(
                        new SpannableStringBuilder(editingMessageObject.caption.toString()),
                        messageEditText.getPaint().getFontMetricsInt(), AndroidUtilities.dp(20), false));
            } else {
                setFieldText("");
            }
        } else {
            inputFilters[0] = new InputFilter.LengthFilter(4096);
            if (editingMessageObject.messageText != null) {
                ArrayList<TLRPC.MessageEntity> entities = editingMessageObject.messageOwner.entities;//MessagesQuery.getEntities(message);
                MessagesQuery.sortEntities(entities);
                SpannableStringBuilder stringBuilder = new SpannableStringBuilder(
                        editingMessageObject.messageText);
                Object spansToRemove[] = stringBuilder.getSpans(0, stringBuilder.length(), Object.class);
                if (spansToRemove != null && spansToRemove.length > 0) {
                    for (int a = 0; a < spansToRemove.length; a++) {
                        stringBuilder.removeSpan(spansToRemove[a]);
                    }
                }
                if (entities != null) {
                    int addToOffset = 0;
                    try {
                        for (int a = 0; a < entities.size(); a++) {
                            TLRPC.MessageEntity entity = entities.get(a);
                            if (entity.offset + entity.length + addToOffset > stringBuilder.length()) {
                                continue;
                            }
                            if (entity instanceof TLRPC.TL_inputMessageEntityMentionName) {
                                if (entity.offset + entity.length + addToOffset < stringBuilder.length()
                                        && stringBuilder
                                                .charAt(entity.offset + entity.length + addToOffset) == ' ') {
                                    entity.length++;
                                }
                                stringBuilder.setSpan(new URLSpanUserMention(
                                        "" + ((TLRPC.TL_inputMessageEntityMentionName) entity).user_id.user_id,
                                        true), entity.offset + addToOffset,
                                        entity.offset + entity.length + addToOffset,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            } else if (entity instanceof TLRPC.TL_messageEntityCode) {
                                stringBuilder.insert(entity.offset + entity.length + addToOffset, "`");
                                stringBuilder.insert(entity.offset + addToOffset, "`");
                                addToOffset += 2;
                            } else if (entity instanceof TLRPC.TL_messageEntityPre) {
                                stringBuilder.insert(entity.offset + entity.length + addToOffset, "```");
                                stringBuilder.insert(entity.offset + addToOffset, "```");
                                addToOffset += 6;
                            } else if (entity instanceof TLRPC.TL_messageEntityBold) {
                                stringBuilder.setSpan(
                                        new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")),
                                        entity.offset + addToOffset,
                                        entity.offset + entity.length + addToOffset,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            } else if (entity instanceof TLRPC.TL_messageEntityItalic) {
                                stringBuilder.setSpan(
                                        new TypefaceSpan(AndroidUtilities.getTypeface("fonts/ritalic.ttf")),
                                        entity.offset + addToOffset,
                                        entity.offset + entity.length + addToOffset,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                        }
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                setFieldText(Emoji.replaceEmoji(stringBuilder, messageEditText.getPaint().getFontMetricsInt(),
                        AndroidUtilities.dp(20), false));
            } else {
                setFieldText("");
            }
        }
        messageEditText.setFilters(inputFilters);
        openKeyboard();
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) messageEditText.getLayoutParams();
        layoutParams.rightMargin = AndroidUtilities.dp(4);
        messageEditText.setLayoutParams(layoutParams);
        sendButton.setVisibility(GONE);
        cancelBotButton.setVisibility(GONE);
        audioVideoButtonContainer.setVisibility(GONE);
        attachLayout.setVisibility(GONE);
        sendButtonContainer.setVisibility(GONE);
    } else {
        doneButtonContainer.setVisibility(View.GONE);
        messageEditText.setFilters(new InputFilter[0]);
        delegate.onMessageEditEnd(false);
        audioVideoButtonContainer.setVisibility(VISIBLE);
        attachLayout.setVisibility(VISIBLE);
        sendButtonContainer.setVisibility(VISIBLE);
        attachLayout.setScaleX(1.0f);
        attachLayout.setAlpha(1.0f);
        sendButton.setScaleX(0.1f);
        sendButton.setScaleY(0.1f);
        sendButton.setAlpha(0.0f);
        cancelBotButton.setScaleX(0.1f);
        cancelBotButton.setScaleY(0.1f);
        cancelBotButton.setAlpha(0.0f);
        audioVideoButtonContainer.setScaleX(1.0f);
        audioVideoButtonContainer.setScaleY(1.0f);
        audioVideoButtonContainer.setAlpha(1.0f);
        sendButton.setVisibility(GONE);
        cancelBotButton.setVisibility(GONE);
        messageEditText.setText("");
        if (getVisibility() == VISIBLE) {
            delegate.onAttachButtonShow();
        }
        updateFieldRight(1);
    }
    updateFieldHint();
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span) {
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan clickable = new ClickableSpan() {
        public void onClick(View view) {
            if (!mLoadingPlugin) {
                mLoadingPlugin = true;/*from   w w  w  .  j a  v  a 2 s .c o  m*/
                String url = span.getURL();

                if (url.startsWith("http://play.google.com/store/apps/details?id=")) {
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW,
                                Uri.parse(url.replace("http://play.google.com/store/apps", "market:/"))));
                    } catch (android.content.ActivityNotFoundException anfe) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    }

                    mLoadingPlugin = false;
                } else if (url.startsWith("plugin://") || url.startsWith("plugins://")) {
                    final File path = IOUtils.getDownloadDirectory(getApplicationContext());

                    if (!path.isDirectory()) {
                        path.mkdirs();
                    }

                    if (url.startsWith("plugin://")) {
                        url = url.replace("plugin://", "http://");
                    } else if (url.startsWith("plugins://")) {
                        url = url.replace("plugins://", "https://");
                    }

                    String name = url.substring(url.lastIndexOf("/") + 1);

                    mCurrentDownloadPlugin = new File(path, name);

                    if (mCurrentDownloadPlugin.isFile()) {
                        mCurrentDownloadPlugin.delete();
                    }

                    final String downloadUrl = url;

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            AsyncTask<String, Void, Boolean> async = new AsyncTask<String, Void, Boolean>() {
                                private ProgressDialog mProgress;
                                private File mPluginFile;

                                protected void onPreExecute() {
                                    mProgress = new ProgressDialog(TvBrowser.this);
                                    mProgress.setMessage(getString(R.string.plugin_info_donwload).replace("{0}",
                                            mCurrentDownloadPlugin.getName()));
                                    mProgress.show();
                                };

                                @Override
                                protected Boolean doInBackground(String... params) {
                                    mPluginFile = new File(params[0]);
                                    return IOUtils.saveUrl(params[0], params[1], 15000);
                                }

                                protected void onPostExecute(Boolean result) {
                                    mProgress.dismiss();

                                    if (result) {
                                        Intent intent = new Intent(Intent.ACTION_VIEW);
                                        intent.setDataAndType(Uri.fromFile(mPluginFile),
                                                "application/vnd.android.package-archive");
                                        TvBrowser.this.startActivityForResult(intent, INSTALL_PLUGIN);
                                    }

                                    mLoadingPlugin = false;
                                };
                            };

                            async.execute(mCurrentDownloadPlugin.toString(), downloadUrl);
                        }
                    });
                } else {
                    mLoadingPlugin = false;
                }
            }
        }
    };
    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}