Example usage for android.text Editable setSpan

List of usage examples for android.text Editable setSpan

Introduction

In this page you can find the example usage for android.text Editable setSpan.

Prototype

public void setSpan(Object what, int start, int end, int flags);

Source Link

Document

Attach the specified markup object to the range start…end of the text, or move the object to that range if it was already attached elsewhere.

Usage

From source file:org.miaowo.miaowo.util.Html.java

private static void startCssStyle(Editable text, Attributes attributes) {
    String style = attributes.getValue("", "style");
    if (style != null) {
        final int len = text.length();
        Matcher m = getForegroundColorPattern().matcher(style);
        if (m.find()) {
            int c = Color.parseColor(m.group(1));
            if (c != -1) {
                text.setSpan(new Foreground(c | 0xFF000000), len, len, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }/*www  . j a  va2s .c o  m*/
        }

        m = getBackgroundColorPattern().matcher(style);
        if (m.find()) {
            int c = Color.parseColor(m.group(1));
            if (c != -1) {
                text.setSpan(new Background(c | 0xFF000000), len, len, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
        }

        m = getTextDecorationPattern().matcher(style);
        if (m.find()) {
            String textDecoration = m.group(1);
            if (textDecoration.equalsIgnoreCase("line-through")) {
                text.setSpan(new Strikethrough(), len, len, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
        }
    }
}

From source file:org.miaowo.miaowo.util.Html.java

private static void startImg(Editable text, Attributes attributes, Html.ImageGetter img, Context context) {
    String src = attributes.getValue("", "src");
    Drawable d = null;/* www  . ja va2s  . co  m*/

    if (img != null) {
        d = img.getDrawable(src);
    }

    if (d == null) {
        d = ResourcesCompat.getDrawable(context.getResources(), R.drawable.unknown_image, null);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    }

    int len = text.length();
    text.append("\uFFFC");

    text.setSpan(new ImageSpan(d, src), len, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

From source file:org.miaowo.miaowo.util.Html.java

private static void endFont(Editable text) {
    int len = text.length();
    Font f = getLast(text, Font.class);
    int where = text.getSpanStart(f);
    text.removeSpan(f);/*from   w ww .  jav  a 2  s .co m*/

    if (where != len) {
        if (!TextUtils.isEmpty(f.mColor)) {
            if (f.mColor.startsWith("@")) {
                Resources res = Resources.getSystem();
                String name = f.mColor.substring(1);
                int colorRes = res.getIdentifier(name, "color", "android");
                if (colorRes != 0) {
                    ColorStateList colors = ResourcesCompat.getColorStateList(res, colorRes, null);
                    text.setSpan(new TextAppearanceSpan(null, 0, 0, colors, null), where, len,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            } else {
                int c = Color.parseColor(f.mColor);
                if (c != -1) {
                    text.setSpan(new ForegroundColorSpan(c | 0xFF000000), where, len,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }

        if (f.mFace != null) {
            text.setSpan(new TypefaceSpan(f.mFace), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}

From source file:tv.acfun.video.CommentsActivity.java

private void initCommentsBar() {
    mCommentBar = findViewById(R.id.comments_bar);
    mBtnSend = (ImageButton) findViewById(R.id.comments_send_btn);
    mCommentText = (EditText) findViewById(R.id.comments_edit);
    mBtnEmotion = findViewById(R.id.comments_emotion_btn);
    mEmotionGrid = (GridView) findViewById(R.id.emotions);
    mBtnSend.setOnClickListener(this);
    mBtnEmotion.setOnClickListener(this);
    mEmotionGrid.setAdapter(mEmotionAdapter);
    mEmotionGrid.setOnItemClickListener(new OnItemClickListener() {

        @Override//from  ww  w  . j  av  a 2 s  .c  o  m
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int index = mCommentText.getSelectionEnd();
            Editable text = mCommentText.getText();
            String emotion = parent.getItemAtPosition(position).toString();
            text.insert(index, emotion);
            EmotionView v = (EmotionView) parent.getAdapter().getView(position, null, null);
            Drawable drawable = TextViewUtils.convertViewToDrawable(v);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 2, drawable.getIntrinsicHeight() / 2);
            text.setSpan(new ImageSpan(drawable), index, index + emotion.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

    });
}

From source file:tv.acfun.a63.CommentsActivity.java

private void initCommentsBar() {
    mCommentBar = findViewById(R.id.comments_bar);

    if (ActionBarUtil.hasSB()
            && getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
        RelativeLayout.LayoutParams params = (LayoutParams) mCommentBar.getLayoutParams();
        params.bottomMargin = getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        mCommentBar.setLayoutParams(params);
    }/*from w w  w .j a v  a2s .  c o m*/
    mBtnSend = (ImageButton) findViewById(R.id.comments_send_btn);
    mCommentText = (EditText) findViewById(R.id.comments_edit);
    mBtnEmotion = findViewById(R.id.comments_emotion_btn);
    mEmotionGrid = (GridView) findViewById(R.id.emotions);
    mBtnSend.setOnClickListener(this);
    mBtnEmotion.setOnClickListener(this);
    mEmotionGrid.setAdapter(mEmotionAdapter);
    mEmotionGrid.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int index = mCommentText.getSelectionEnd();
            Editable text = mCommentText.getText();
            String emotion = parent.getItemAtPosition(position).toString();
            text.insert(index, emotion);
            EmotionView v = (EmotionView) parent.getAdapter().getView(position, null, null);
            Drawable drawable = TextViewUtils.convertViewToDrawable(v);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 2, drawable.getIntrinsicHeight() / 2);
            text.setSpan(new ImageSpan(drawable), index, index + emotion.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

    });
}

From source file:com.taobao.weex.dom.WXTextDomObject.java

/**
 * Truncate the source span to the specified lines.
 * Caller of this method must ensure that the lines of text is <strong>greater than desired lines and need truncate</strong>.
 * Otherwise, unexpected behavior may happen.
 * @param source The source span.//from   w  ww.  j a va  2 s  .co m
 * @param paint the textPaint
 * @param desired specified lines.
 * @param truncateAt truncate method, null value means clipping overflow text directly, non-null value means using ellipsis strategy to clip
 * @return The spans after clipped.
 */
private @NonNull Spanned truncate(@Nullable Editable source, @NonNull TextPaint paint, int desired,
        @Nullable TextUtils.TruncateAt truncateAt) {
    Spanned ret = new SpannedString("");
    if (!TextUtils.isEmpty(source) && source.length() > 0) {
        if (truncateAt != null) {
            source.append(ELLIPSIS);
            Object[] spans = source.getSpans(0, source.length(), Object.class);
            for (Object span : spans) {
                int start = source.getSpanStart(span);
                int end = source.getSpanEnd(span);
                if (start == 0 && end == source.length() - 1) {
                    source.removeSpan(span);
                    source.setSpan(span, 0, source.length(), source.getSpanFlags(span));
                }
            }
        }

        StaticLayout layout;
        int startOffset;

        while (source.length() > 1) {
            startOffset = source.length() - 1;
            if (truncateAt != null) {
                startOffset -= 1;
            }
            source.delete(startOffset, startOffset + 1);
            layout = new StaticLayout(source, paint, desired, Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
            if (layout.getLineCount() <= 1) {
                ret = source;
                break;
            }
        }
    }
    return ret;
}

From source file:com.ruesga.rview.widget.TagEditTextView.java

private void createChip(Editable s, boolean nextIsTag) {
    int start = mTagList.size();
    int end = s.length() + (nextIsTag ? -1 : 0);
    String tagText = s.subSequence(start, end).toString().trim();
    tagText = NON_UNICODE_CHAR_PATTERN.matcher(tagText).replaceAll("");
    if (tagText.isEmpty() || tagText.length() <= 1) {
        // User is still writing
        return;/*from w  w w .  j  av  a  2  s. c om*/
    }
    String charText = tagText.substring(0, 1);
    if (!VALID_TAGS.contains(charText) || (charText.charAt(0) == VALID_TAGS.charAt(1) && !mSupportsUserTags)) {
        char tag = mDefaultTagMode == TAG_MODE.HASH ? VALID_TAGS.charAt(0) : VALID_TAGS.charAt(1);
        tagText = tag + tagText;
    }

    // Replace the new tag
    s.replace(start, end, CHIP_REPLACEMENT_CHAR);

    // Create the tag and its spannable
    final Tag tag = new Tag();
    tag.mTag = NON_UNICODE_CHAR_PATTERN.matcher(tagText).replaceAll("");
    Bitmap b = createTagChip(tag);
    ImageSpan span = new ImageSpan(getContext(), b);
    s.setSpan(span, start, start + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    tag.w = b.getWidth();
    tag.h = b.getHeight();
    mTagList.add(tag);

    notifyTagCreated(tag);
}

From source file:com.android.ex.chips.RecipientEditTextView.java

/**
 * Remove selection from this chip. Unselecting a RecipientChip will render the chip without a delete icon and with
 * an unfocused background. This is called when the RecipientChip no longer has focus.
 *///w w  w . j  a va2s.  co  m
private void unselectChip(final DrawableRecipientChip chip) {
    final int start = getChipStart(chip);
    final int end = getChipEnd(chip);
    final Editable editable = getText();
    mSelectedChip = null;
    if (start == -1 || end == -1) {
        Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
        setSelection(editable.length());
        commitDefault();
    } else {
        getSpannable().removeSpan(chip);
        QwertyKeyListener.markAsReplaced(editable, start, end, "");
        editable.removeSpan(chip);
        try {
            if (!mNoChips)
                editable.setSpan(constructChipSpan(chip.getEntry(), false, false), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (final NullPointerException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }
    setCursorVisible(true);
    setSelection(editable.length());
    /*if(mAlternatesPopup!=null&&mAlternatesPopup.isShowing())
      mAlternatesPopup.dismiss();*/
}

From source file:cgeo.geocaching.CacheDetailActivity.java

private void addWarning(final UnknownTagsHandler unknownTagsHandler, final Editable description) {
    if (unknownTagsHandler.isProblematicDetected()) {
        final int startPos = description.length();
        final IConnector connector = ConnectorFactory.getConnector(cache);
        if (StringUtils.isNotEmpty(cache.getUrl())) {
            final Spanned tableNote = Html.fromHtml(res.getString(R.string.cache_description_table_note,
                    "<a href=\"" + cache.getUrl() + "\">" + connector.getName() + "</a>"));
            description.append("\n\n").append(tableNote);
            description.setSpan(new StyleSpan(Typeface.ITALIC), startPos, description.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }//  w w w  . jav  a 2 s .  c o  m
    }
}

From source file:com.android.ex.chips.RecipientEditTextView.java

/**
 * Replace the more chip, if it exists, with all of the recipient chips it had replaced when the
 * RecipientEditTextView gains focus.//from  w w w. j  a  v a  2  s  . c om
 */
// Visible for testing.
/* package */void removeMoreChip() {
    if (mMoreChip != null) {
        final 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.
            final 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]);
            final Editable editable = getText();
            for (final 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, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            mRemovedSpans.clear();
        }
    }
}