android.text.Spannable Java Examples

The following examples show how to use android.text.Spannable. 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: TextViewLinkHandler.java    From Slide with GNU General Public License v3.0 6 votes vote down vote up
public TextViewLinkHandler(ClickableText clickableText, String subreddit, Spannable sequence) {
    this.clickableText = clickableText;
    this.subreddit = subreddit;
    this.sequence = sequence;

    clickHandled = false;
    handler = new Handler();
    longClicked = new Runnable() {
        @Override
        public void run() {
            // long click
            clickHandled = true;

            handler.removeCallbacksAndMessages(null);
            if (link != null && link.length > 0 && link[0] != null) {
                TextViewLinkHandler.this.clickableText.onLinkLongClick(link[0].getURL(), event);
            }

        }
    };
}
 
Example #2
Source File: CustomHtmlToSpannedConverter.java    From zulip-android with Apache License 2.0 6 votes vote down vote up
private static void endHeader(SpannableStringBuilder text) {
    int len = text.length();
    Object obj = getLast(text, Header.class);

    int where = text.getSpanStart(obj);

    text.removeSpan(obj);

    // Back off not to change only the text, not the blank line.
    while (len > where && text.charAt(len - 1) == '\n') {
        len--;
    }

    if (where != len) {
        Header h = (Header) obj;

        text.setSpan(new RelativeSizeSpan(HEADER_SIZES[h.mLevel]), where,
                len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.setSpan(new StyleSpan(Typeface.BOLD), where, len,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
}
 
Example #3
Source File: CheckForNewMessages.java    From SteamGifts with MIT License 6 votes vote down vote up
/**
 * Returns the comment's content, and, optionally, the author's name
 *
 * @param comment     comment to display the content of
 * @param includeName whether or not to include the author's name
 * @return text to display in the notification
 */
@NonNull
private CharSequence formatComment(Comment comment, boolean includeName) {
    String content = StringUtils.fromHtml(context, comment.getContent()).toString();
    if (TextUtils.isEmpty(content) && comment.getAttachedImages() != null && comment.getAttachedImages().size() > 0) {
        content = context.getString(R.string.notification_has_attached_image);
    }

    if (includeName && comment.getAuthor() != null) {
        SpannableString sb = new SpannableString(String.format("%s  %s", comment.getAuthor(), content));
        sb.setSpan(new StyleSpan(Typeface.BOLD), 0, comment.getAuthor().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    } else {
        return content;
    }
}
 
Example #4
Source File: WizardPage2Activity.java    From secure-quick-reliable-login with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Utils.setLanguage(this);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.startup_wizard_page_2);

    TextView wizardText = findViewById(R.id.wizard_text);
    String s = (String)wizardText.getText();
    Spannable textSpan = Utils.getSpanWithHighlight(s);
    wizardText.setText(textSpan);

    Button next = findViewById(R.id.wizard_next);
    next.setOnClickListener((a) -> {
        startActivity(new Intent(this, WizardPage3Activity.class));
    });
    Button skip = findViewById(R.id.wizard_skip);
    skip.setOnClickListener((a) -> {
        startActivity(new Intent(this, StartActivity.class));
    });
}
 
Example #5
Source File: PayerCostFormatter.java    From px-android with MIT License 6 votes vote down vote up
public Spannable apply() {
    Spannable totalAmount = new SpannableStringBuilder();
    if (payerCost.getInstallments() > 1) {
        totalAmount = TextFormatter.withCurrency(currency)
            .amount(payerCost.getTotalAmount())
            .normalDecimals()
            .apply(R.string.px_total_amount_holder, context);
    }

    final int initialIndex = spannableStringBuilder.length();
    final String separator = " ";
    spannableStringBuilder.append(separator).append(totalAmount);
    final int textLength = separator.length() + totalAmount.length();
    final int endIndex = initialIndex + textLength;

    ViewUtils.setColorInSpannable(textColor, initialIndex, endIndex, spannableStringBuilder);
    ViewUtils.setFontInSpannable(context, PxFont.REGULAR, spannableStringBuilder, initialIndex, endIndex);

    return spannableStringBuilder;
}
 
Example #6
Source File: CommentsAdapter.java    From mentions with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #7
Source File: GoURLSpan.java    From droidddle with Apache License 2.0 6 votes vote down vote up
/**
 * @param spanText
 * @return true if have url
 */
public static final boolean hackURLSpanHasResult(SpannableStringBuilder spanText) {
    boolean result = false;
    URLSpan[] spans = spanText.getSpans(0, spanText.length(), URLSpan.class);
    // TODO URLSpan need change to ClickableSpan (GoURLSpan) , otherwise URLSpan can not click, not display underline.WHY?
    for (URLSpan span : spans) {
        int start = spanText.getSpanStart(span);
        int end = spanText.getSpanEnd(span);
        String url = span.getURL();
        if (url != null) {
            result = true;
            spanText.removeSpan(span);
            ClickableSpan span1 = new GoURLSpan(span.getURL());
            spanText.setSpan(span1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    return result;
}
 
Example #8
Source File: LongClickableLinkMovementMethod.java    From RichEditor with MIT License 6 votes vote down vote up
private BlockImageSpan getPressedSpan(TextView textView, Spannable spannable, MotionEvent event) {
    int x = (int) event.getX() - textView.getTotalPaddingLeft() + textView.getScrollX();
    int y = (int) event.getY() - textView.getTotalPaddingTop() + textView.getScrollY();

    Layout layout = textView.getLayout();
    int position = layout.getOffsetForHorizontal(layout.getLineForVertical(y), x);

    BlockImageSpan[] blockImageSpans = spannable.getSpans(position, position, BlockImageSpan.class);
    BlockImageSpan touchedSpan = null;
    if (blockImageSpans.length > 0 && positionWithinTag(position, spannable, blockImageSpans[0])
        && blockImageSpans[0].clicked(x, y)) {
        touchedSpan = blockImageSpans[0];
    }

    return touchedSpan;
}
 
Example #9
Source File: RecipientEditTextView.java    From ChipsLibrary with Apache License 2.0 6 votes vote down vote up
DrawableRecipientChip[] getSortedRecipients()
{
final DrawableRecipientChip[] recips=getSpannable().getSpans(0,getText().length(),DrawableRecipientChip.class);
final ArrayList<DrawableRecipientChip> recipientsList=new ArrayList<DrawableRecipientChip>(Arrays.asList(recips));
final Spannable spannable=getSpannable();
Collections.sort(recipientsList,new Comparator<DrawableRecipientChip>()
  {
    @Override
    public int compare(final DrawableRecipientChip first,final DrawableRecipientChip second)
      {
      final int firstStart=spannable.getSpanStart(first);
      final int secondStart=spannable.getSpanStart(second);
      if(firstStart<secondStart)
        return -1;
      else if(firstStart>secondStart)
        return 1;
      else return 0;
      }
  });
return recipientsList.toArray(new DrawableRecipientChip[recipientsList.size()]);
}
 
Example #10
Source File: ArrowKeyMovementMethod.java    From JotaTextEditor with Apache License 2.0 6 votes vote down vote up
private boolean down(TextView widget, Spannable buffer) {
        boolean cap = (MetaKeyKeyListener.getMetaState(buffer,
                        KeyEvent.META_SHIFT_ON) == 1) ||
                      (JotaTextKeyListener.getMetaStateSelecting(buffer) != 0);
        boolean alt = MetaKeyKeyListener.getMetaState(buffer,
                        KeyEvent.META_ALT_ON) == 1;
        Layout layout = widget.getLayout();

        if (cap) {
            if (alt) {
//                Selection.extendSelection(buffer, buffer.length());
                widget.movePage(false,true);
                return true;
            } else {
                return Selection.extendDown(buffer, layout);
            }
        } else {
            if (alt) {
//                Selection.setSelection(buffer, buffer.length());
                widget.movePage(false,false);
                return true;
            } else {
                return Selection.moveDown(buffer, layout);
            }
        }
    }
 
Example #11
Source File: CensoredTextHolderEx.java    From actor-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #12
Source File: ComposeText.java    From deltachat-android with GNU General Public License v3.0 6 votes vote down vote up
public void setHint(@NonNull String hint, @Nullable CharSequence subHint) {
  this.hint = hint;

  if (subHint != null) {
    this.subHint = new SpannableString(subHint);
    this.subHint.setSpan(new RelativeSizeSpan(0.5f), 0, subHint.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
  } else {
    this.subHint = null;
  }

  if (this.subHint != null) {
    super.setHint(new SpannableStringBuilder().append(ellipsizeToWidth(this.hint))
                                              .append("\n")
                                              .append(ellipsizeToWidth(this.subHint)));
  } else {
    super.setHint(ellipsizeToWidth(this.hint));
  }
}
 
Example #13
Source File: RTEditorMovementMethod.java    From Android-RTEditor with Apache License 2.0 6 votes vote down vote up
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
    int action = event.getAction();

    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {

        int index = getCharIndexAt(widget, event);
        if (index != -1) {
            ClickableSpan[] link = buffer.getSpans(index, index, ClickableSpan.class);
            if (link.length != 0) {
                if (action == MotionEvent.ACTION_UP) {
                    link[0].onClick(widget);
                } else if (action == MotionEvent.ACTION_DOWN) {
                    Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]));
                }
                return true;
            }
        }
        /*else {
            Selection.removeSelection(buffer);
        }*/

    }

    return super.onTouchEvent(widget, buffer, event);
}
 
Example #14
Source File: QBMessageTextClickMovement.java    From ChatMessagesAdapter-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String getLinkText(final TextView widget, final Spannable buffer, final MotionEvent event) {

            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

            if (link.length != 0) {
                return buffer.subSequence(buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0])).toString();
            }

            return buffer.toString();
        }
 
Example #15
Source File: RTEditText.java    From memoir with Apache License 2.0 6 votes vote down vote up
/**
 * Call this to have an effect applied to the current selection.
 * You get the Effect object via the static data members (e.g., RTEditText.BOLD).
 * The value for most effects is a Boolean, indicating whether to add or remove the effect.
 */
public <V extends Object, C extends RTSpan<V>> void applyEffect(Effect<V, C> effect, V value) {
    if (mUseRTFormatting && !mIsSelectionChanging && !mIsSaving) {
        Spannable oldSpannable = mIgnoreTextChanges ? null : cloneSpannable();

        effect.applyToSelection(this, value);

        synchronized (this) {
            if (mListener != null && !mIgnoreTextChanges) {
                Spannable newSpannable = cloneSpannable();
                mListener.onTextChanged(this, oldSpannable, newSpannable, getSelectionStart(), getSelectionEnd(),
                                        getSelectionStart(), getSelectionEnd());
            }
            mLayoutChanged = true;
        }
    }
}
 
Example #16
Source File: ArrowKeyMovementMethod.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean pageDown(TextView widget, Spannable buffer) {
    final Layout layout = widget.getLayout();
    final boolean selecting = isSelecting(buffer);
    final int targetY = getCurrentLineTop(buffer, layout) + getPageHeight(widget);
    boolean handled = false;
    for (;;) {
        final int previousSelectionEnd = Selection.getSelectionEnd(buffer);
        if (selecting) {
            Selection.extendDown(buffer, layout);
        } else {
            Selection.moveDown(buffer, layout);
        }
        if (Selection.getSelectionEnd(buffer) == previousSelectionEnd) {
            break;
        }
        handled = true;
        if (getCurrentLineTop(buffer, layout) >= targetY) {
            break;
        }
    }
    return handled;
}
 
Example #17
Source File: QiscusBaseImageMessageViewHolder.java    From qiscus-sdk-android with Apache License 2.0 6 votes vote down vote up
protected void showCaption(QiscusComment qiscusComment) {
    if (captionView != null) {
        captionView.setVisibility(TextUtils.isEmpty(qiscusComment.getCaption()) ? View.GONE : View.VISIBLE);
        QiscusMentionConfig mentionConfig = Qiscus.getChatConfig().getMentionConfig();
        if (mentionConfig.isEnableMention()) {
            Spannable spannable = QiscusTextUtil.createQiscusSpannableText(
                    qiscusComment.getCaption(),
                    roomMembers,
                    messageFromMe ? mentionConfig.getRightMentionAllColor() : mentionConfig.getLeftMentionAllColor(),
                    messageFromMe ? mentionConfig.getRightMentionOtherColor() : mentionConfig.getLeftMentionOtherColor(),
                    messageFromMe ? mentionConfig.getRightMentionMeColor() : mentionConfig.getLeftMentionMeColor(),
                    mentionConfig.getMentionClickHandler()
            );
            captionView.setText(spannable);
        } else {
            captionView.setText(qiscusComment.getCaption());
        }
    }
}
 
Example #18
Source File: CharSequenceUtils.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
public static List<CharSequence> split(Spannable charSequence, char c) {
    List<CharSequence> out = new ArrayList<>();
    int begin = 0;
    for (int i = 0; i < charSequence.length(); ++i) {
        if (charSequence.charAt(i) == c) {
            out.add(StylingHelper.subSequence(charSequence, begin, i));
            begin = ++i;
        }
    }
    if (begin < charSequence.length()) {
        out.add(StylingHelper.subSequence(charSequence, begin, charSequence.length()));
    }
    return out;
}
 
Example #19
Source File: TranscriptionResultFormatter.java    From live-transcribe-speech-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a {@link SpannableString} containing a colored string.
 *
 * @param message a string to append to cachedFinalizedResult
 * @param color a six-character hex string beginning with a pound sign
 */
private SpannableString makeColoredString(String message, String color) {
  int textColor = Color.parseColor(color);
  SpannableString spannableString = new SpannableString(message);
  spannableString.setSpan(
      new ForegroundColorSpan(textColor),
      0,
      spannableString.length(),
      Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  return spannableString;
}
 
Example #20
Source File: DataWrapper.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
static String getProfileNameWithManualIndicatorAsString(
        Profile profile, boolean addEventName, String indicators, boolean addDuration, boolean multiLine,
        boolean durationInNextLine, DataWrapper dataWrapper) {
    Spannable sProfileName = getProfileNameWithManualIndicator(profile, addEventName, indicators, addDuration, multiLine, durationInNextLine, dataWrapper);
    Spannable sbt = new SpannableString(sProfileName);
    Object[] spansToRemove = sbt.getSpans(0, sProfileName.length(), Object.class);
    for (Object span : spansToRemove) {
        if (span instanceof CharacterStyle)
            sbt.removeSpan(span);
    }
    return sbt.toString();
}
 
Example #21
Source File: ArrowKeyMovementMethod.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean up(TextView widget, Spannable buffer) {
    final Layout layout = widget.getLayout();
    if (isSelecting(buffer)) {
        return Selection.extendUp(buffer, layout);
    } else {
        return Selection.moveUp(buffer, layout);
    }
}
 
Example #22
Source File: SuggestionsAdapter.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private CharSequence formatUrl(Context context, CharSequence url) {
    if (mUrlColor == null) {
        // Lazily get the URL color from the current theme.
        TypedValue colorValue = new TypedValue();
        context.getTheme().resolveAttribute(R.attr.textColorSearchUrl, colorValue, true);
        mUrlColor = context.getColorStateList(colorValue.resourceId);
    }

    SpannableString text = new SpannableString(url);
    text.setSpan(new TextAppearanceSpan(null, 0, 0, mUrlColor, null),
            0, url.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return text;
}
 
Example #23
Source File: BaseRichEditText.java    From nono-android with GNU General Public License v3.0 5 votes vote down vote up
public void applyColorSpan(Class type, @ColorInt int color){
    int selStart=getSelectionStart();
    int selEnd=getSelectionEnd();
    if(selEnd-selStart>0){
        Object[] ss = getEditableText().getSpans(selStart, selEnd, type);
        for (Object span:ss) {
            removeSpan(span,selStart,selEnd);
        }
        if (type == BackgroundColorSpan.class) {
            //toggleBackgroundColor();
            if(isBackgroundColor){
                colorFontBackground=color;
                setSpan(new BackgroundColorSpan(color),selStart,selEnd,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        } else if (type == ForegroundColorSpan.class) {
            //toggleForegroundColor();
            if(isForegroundColor){
                colorFontForeground=color;
                setSpan(new ForegroundColorSpan(color),selStart,selEnd,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }else if(selEnd==selStart){
        if (type == BackgroundColorSpan.class) {
            //toggleBackgroundColor();
            colorFontBackground=color;
        } else if (type == ForegroundColorSpan.class) {
            //toggleForegroundColor();
            colorFontForeground=color;
        }
    }
}
 
Example #24
Source File: LinkMovementMethod2.java    From EhViewer with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean up(TextView widget, Spannable buffer) {
    if (action(UP, widget, buffer)) {
        return true;
    }

    return super.up(widget, buffer);
}
 
Example #25
Source File: RecordDetailActivity.java    From UPMiss with GNU General Public License v3.0 5 votes vote down vote up
private CharSequence getTopText(int occupancy) {
    SpannableStringBuilder span = new SpannableStringBuilder();

    int lenFx = SUFFIX.length();

    if (occupancy < 0) {
        occupancy = -occupancy;
        span.append(String.valueOf(occupancy));
        span.append('\n');
        span.append('-');
        lenFx += 2;
    } else {
        span.append(String.valueOf(occupancy));
        span.append('\n');
        lenFx += 1;
    }
    span.append(SUFFIX);

    final Resources resources = getResources();
    final int len = span.length();
    lenFx = len - lenFx;

    span.setSpan(new AbsoluteSizeSpan(resources.getDimensionPixelSize(R.dimen.font_14)),
            lenFx, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    span.setSpan(new ForegroundColorSpan(resources.getColor(R.color.grey_500)),
            lenFx, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return span;
}
 
Example #26
Source File: MessageAdapter.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
private void applyQuoteSpan(SpannableStringBuilder body, int start, int end, boolean darkBackground) {
    if (start > 1 && !"\n\n".equals(body.subSequence(start - 2, start).toString())) {
        body.insert(start++, "\n");
        body.setSpan(new DividerSpan(false), start - 2, start, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        end++;
    }
    if (end < body.length() - 1 && !"\n\n".equals(body.subSequence(end, end + 2).toString())) {
        body.insert(end, "\n");
        body.setSpan(new DividerSpan(false), end, end + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    int color = darkBackground ? this.getMessageTextColor(darkBackground, false)
            : ContextCompat.getColor(activity, R.color.green700_desaturated);
    DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
    body.setSpan(new QuoteSpan(color, metrics), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
 
Example #27
Source File: LinkMovementMethod.java    From ForPDA with GNU General Public License v3.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 #28
Source File: TextInlineImageSpan.java    From react-native-GPay with MIT License 5 votes vote down vote up
/**
 * For TextInlineImageSpan we need to update the Span to know that the window is attached and
 * the TextView that we will set as the callback on the Drawable.
 *
 * @param spannable The spannable that may contain TextInlineImageSpans
 * @param view The view which will be set as the callback for the Drawable
 */
public static void possiblyUpdateInlineImageSpans(Spannable spannable, TextView view) {
  TextInlineImageSpan[] spans =
    spannable.getSpans(0, spannable.length(), TextInlineImageSpan.class);
  for (TextInlineImageSpan span : spans) {
    span.onAttachedToWindow();
    span.setTextView(view);
  }
}
 
Example #29
Source File: SmileyReader.java    From AndFChat with GNU General Public License v3.0 5 votes vote down vote up
public static Spannable addSmileys(Context context, Spannable text) {
    for (Entry<Pattern, Integer> entry : emoticons.entrySet()) {
        Matcher matcher = entry.getKey().matcher(text);
        while (matcher.find()) {
            text.setSpan(new ImageSpan(context, entry.getValue()), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
            
    return text;        
}
 
Example #30
Source File: SocialMentionTextView.java    From SocialMentionAutoComplete with Apache License 2.0 5 votes vote down vote up
public void setMentionText(String text) {

        originalString = text;

        ArrayMap<String, MentionPerson> map = new ArrayMap<>();

        Pattern p = Pattern.compile("\\[([^]]+)]\\(([^ )]+)\\)");
        Matcher m = p.matcher(text);
        String finalDesc = text;

        while (m.find()) {

            String name = m.group(1);
            String id = m.group(2);
            /*
             * My way of formatting the input i get to the out i need conversion
             * my input : @[Sajesh Cc](user:665c23720db84014ae3f83c67aca8046)
             * my out : @Sajesh Cc
             * */

            finalDesc = finalDesc.replace("@[" + name + "](" + id + ")", "@" + name);

            MentionPerson mentionPerson = new MentionPerson();
            mentionPerson.name = name;
            mentionPerson.id = id;
            map.put("@" + name, mentionPerson);
        }

        Spannable spannable = new SpannableString(finalDesc);
        for (Map.Entry<String, MentionPerson> stringMentionPersonEntry : map.entrySet()) {
            int startIndex = finalDesc.indexOf(stringMentionPersonEntry.getKey());
            int endIndex = startIndex + stringMentionPersonEntry.getKey().length();
            InternalURLSpan internalURLSpan   = new InternalURLSpan();
            internalURLSpan.text = stringMentionPersonEntry.getKey();
            spannable.setSpan(internalURLSpan, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        setText(spannable);
    }