Example usage for android.text SpannableStringBuilder SpannableStringBuilder

List of usage examples for android.text SpannableStringBuilder SpannableStringBuilder

Introduction

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

Prototype

public SpannableStringBuilder(CharSequence text) 

Source Link

Document

Create a new SpannableStringBuilder containing a copy of the specified text, including its spans if any.

Usage

From source file:com.googlecode.eyesfree.brailleback.SelfBrailleService.java

public DisplayManager.Content contentForNode(AccessibilityNodeInfoCompat node) {
    if (mNodeStates.isEmpty()) {
        return null;
    }//from   ww  w.  j a  va 2  s.  c  o m
    AccessibilityNodeInfoCompat match = AccessibilityNodeInfoUtils.getSelfOrMatchingAncestor(this, node,
            mFilterHaveNodeState);
    if (match == null) {
        return null;
    }
    AccessibilityNodeInfo unwrappedMatch = (AccessibilityNodeInfo) match.getInfo();
    WriteData writeData = mNodeStates.get(unwrappedMatch).mWriteData;
    if (writeData == null) {
        return null;
    }
    SpannableStringBuilder sb = new SpannableStringBuilder(writeData.getText());
    // NOTE: it is important to use a node returned by the accessibility
    // framework and not a node from a client of this service.
    // The rest of BrailleBack will assume that the node we are adding
    // here is sealed, supports actions etc.
    DisplaySpans.setAccessibilityNode(sb, match);
    int selectionStart = writeData.getSelectionStart();
    if (selectionStart >= 0) {
        int selectionEnd = writeData.getSelectionEnd();
        if (selectionEnd < selectionStart) {
            selectionEnd = selectionStart;
        }
        DisplaySpans.addSelection(sb, selectionStart, selectionEnd);
    }
    return new DisplayManager.Content(sb).setFirstNode(match).setLastNode(match)
            .setPanStrategy(DisplayManager.Content.PAN_CURSOR);
}

From source file:com.liferay.mobile.screens.viewsets.westeros.auth.signup.SignUpView.java

private void initClickableTermsAndConditions() {
    TextView textView = (TextView) findViewById(R.id.terms);
    textView.setMovementMethod(LinkMovementMethod.getInstance());

    SpannableStringBuilder ssb = new SpannableStringBuilder("I accept the terms and conditions");

    ssb.setSpan(new ClickableSpan() {
        @Override/*from  w  w w .j  a v  a 2s.c  o  m*/
        public void onClick(View widget) {
            SignUpScreenlet signUpScreenlet = getSignUpScreenlet();
            signUpScreenlet.performUserAction(SignUpScreenlet.TERMS_AND_CONDITIONS);
        }
    }, 13, ssb.length(), 0);

    ssb.setSpan(new StyleSpan(Typeface.BOLD), 13, ssb.length(), 0);
    ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), android.R.color.white)), 13,
            ssb.length(), 0);

    textView.setText(ssb, TextView.BufferType.SPANNABLE);
}

From source file:org.kontalk.ui.view.ConversationListItem.java

public final void bind(Context context, final Conversation conv) {
    mConversation = conv;//from   w  w w. j  a  v  a2s .c  o m

    setChecked(false);

    Contact contact;
    // used for the conversation subject: either group subject or contact name
    String recipient = null;

    if (mConversation.isGroupChat()) {
        recipient = mConversation.getGroupSubject();
        if (TextUtils.isEmpty(recipient))
            recipient = context.getString(R.string.group_untitled);

        loadAvatar(null);
    } else {
        contact = mConversation.getContact();

        if (contact != null) {
            recipient = contact.getDisplayName();
        }

        if (recipient == null) {
            if (BuildConfig.DEBUG) {
                recipient = conv.getRecipient();
            } else {
                recipient = context.getString(R.string.peer_unknown);
            }
        }

        loadAvatar(contact);
    }

    SpannableStringBuilder from = new SpannableStringBuilder(recipient);
    if (conv.getUnreadCount() > 0)
        from.setSpan(STYLE_BOLD, 0, from.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

    // draft indicator
    int lastpos = from.length();
    String draft = conv.getDraft();
    if (draft != null) {
        from.append(" ");
        from.append(context.getResources().getString(R.string.has_draft));
        from.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.text_color_draft)),
                lastpos, from.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    mFromView.setText(from);
    mDateView.setText(MessageUtils.formatTimeStampString(context, conv.getDate()));
    mSticky.setVisibility(conv.isSticky() ? VISIBLE : GONE);

    // error indicator
    int resId = -1;
    int statusId = -1;
    switch (conv.getStatus()) {
    case Messages.STATUS_SENDING:
        // use pending icon even for errors
    case Messages.STATUS_ERROR:
    case Messages.STATUS_PENDING:
    case Messages.STATUS_QUEUED:
        resId = R.drawable.ic_msg_pending;
        statusId = R.string.msg_status_sending;
        break;
    case Messages.STATUS_SENT:
        resId = R.drawable.ic_msg_sent;
        statusId = R.string.msg_status_sent;
        break;
    case Messages.STATUS_RECEIVED:
        resId = R.drawable.ic_msg_delivered;
        statusId = R.string.msg_status_delivered;
        break;
    // here we use the error icon
    case Messages.STATUS_NOTACCEPTED:
        resId = R.drawable.ic_thread_error;
        statusId = R.string.msg_status_notaccepted;
        break;
    case Messages.STATUS_NOTDELIVERED:
        resId = R.drawable.ic_msg_notdelivered;
        statusId = R.string.msg_status_notdelivered;
        break;
    }

    // no matching resource or draft - hide status icon
    boolean incoming = resId < 0;
    if (incoming || draft != null) {
        mErrorIndicator.setVisibility(GONE);

        int unread = mConversation.getUnreadCount();
        if (unread > 0) {
            mCounterView.setText(String.valueOf(unread));
            mCounterView.setVisibility(VISIBLE);
        } else {
            mCounterView.setVisibility(GONE);
        }
    } else {
        mCounterView.setVisibility(GONE);
        mErrorIndicator.setVisibility(VISIBLE);
        mErrorIndicator.setImageResource(resId);
        mErrorIndicator.setContentDescription(getResources().getString(statusId));
    }

    CharSequence text;

    // last message or draft??
    if (conv.getRequestStatus() == Threads.REQUEST_WAITING) {
        text = new SpannableString(context.getString(R.string.text_invitation_info));
        ((Spannable) text).setSpan(STYLE_ITALIC, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    } else {
        String subject = conv.getSubject();
        String source = (draft != null) ? draft : subject;

        if (source != null) {
            if (GroupCommandComponent.supportsMimeType(conv.getMime()) && draft == null) {
                if (incoming) {
                    // content is in a special format
                    GroupThreadContent parsed = GroupThreadContent.parseIncoming(subject);
                    subject = parsed.command;
                }
                text = new SpannableString(
                        GroupCommandComponent.getTextContent(getContext(), subject, incoming));
                ((Spannable) text).setSpan(STYLE_ITALIC, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            } else {
                if (incoming && conv.isGroupChat()) {
                    // content is in a special format
                    GroupThreadContent parsed = GroupThreadContent.parseIncoming(subject);
                    contact = parsed.sender != null ? Contact.findByUserId(context, parsed.sender) : null;
                    source = parsed.command;

                    String displayName = null;
                    if (contact != null)
                        displayName = contact.getDisplayName();

                    if (displayName == null) {
                        if (BuildConfig.DEBUG) {
                            displayName = conv.getRecipient();
                        } else {
                            displayName = context.getString(R.string.peer_unknown);
                        }
                    }

                    if (source == null) {
                        // determine from mime type
                        source = CompositeMessage.getSampleTextContent(conv.getMime());
                    }

                    text = new SpannableString(displayName + ": " + source);
                    ((Spannable) text).setSpan(STYLE_ITALIC, 0, displayName.length() + 1,
                            Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                } else {
                    text = source;
                }
            }
        }

        else if (conv.isEncrypted()) {
            text = context.getString(R.string.text_encrypted);
        }

        else {
            // determine from mime type
            text = CompositeMessage.getSampleTextContent(conv.getMime());
        }
    }

    if (conv.getUnreadCount() > 0) {
        text = new SpannableString(text);
        ((Spannable) text).setSpan(STYLE_BOLD, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    mSubjectView.setText(text);
}

From source file:com.madgag.agit.RepoListFragment.java

private SpannableStringBuilder clickableWelcomeMessage() {
    SpannableStringBuilder message = new SpannableStringBuilder(getString(welcome_message));

    applyToEntireString(message, new TextAppearanceSpan(getActivity(), R.style.WelcomeText));
    final Context applicationContext = getActivity().getApplicationContext();
    CharacterStyle linkStyle = new ForegroundColorSpan(getResources().getColor(R.color.link_text));
    ClickableText.addLinks(message, linkStyle, new ClickableText.Listener() {
        public void onClick(String command, View widget) {
            if (command.equals("clone")) {
                startActivity(new Intent(applicationContext, CloneLauncherActivity.class));
            }// w w w  . ja  v  a 2  s  .  c o  m
        }
    });
    return message;
}

From source file:org.openlmis.core.view.viewmodel.InventoryViewModel.java

private void formatProductDisplay(Product product) {
    String productName = product.getFormattedProductName();
    styledName = new SpannableStringBuilder(productName);
    styledName.setSpan(/*from   w  w  w . java2 s.  co m*/
            new ForegroundColorSpan(LMISApp.getContext().getResources().getColor(R.color.color_text_secondary)),
            product.getPrimaryName().length(), productName.length(), Spannable.SPAN_POINT_MARK);

    String unit = product.getStrength() + " " + product.getType();
    styledUnit = new SpannableStringBuilder(unit);
    int length = 0;
    if (product.getStrength() != null) {
        length = product.getStrength().length();
    }
    styledUnit.setSpan(
            new ForegroundColorSpan(LMISApp.getContext().getResources().getColor(R.color.color_text_secondary)),
            length, unit.length(), Spannable.SPAN_POINT_MARK);
}

From source file:io.github.marktony.espresso.mvp.companydetails.CompanyDetailFragment.java

@Override
public void setCompanyName(String name) {
    String companyName = getString(R.string.company_name) + "\n" + name;
    Spannable spannable = new SpannableStringBuilder(companyName);
    spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, companyName.length() - name.length() - 1,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannable.setSpan(new StyleSpan(Typeface.NORMAL), companyName.length() - name.length(),
            companyName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textViewCompanyName.setText(spannable);
}

From source file:com.google.android.apps.common.testing.accessibility.framework.AccessibilityCheckUtils.java

/**
 * Retrieve text for a {@link View}, which may include text from the children of the {@code View}.
 * This text is an approximation of, but not identical to, what TalkBack would speak for the
 * {@link View}. One difference is that there are no separators between the speakable text from
 * different nodes.//w w  w  . jav  a  2s. c o m
 * <p>
 * TalkBack also will not speak {@link View}s that aren't visible. This method assumes that the
 * {@link View} passed in is visible. The visibility of the rest of child nodes is inferred from
 * {@code view.getVisibility}.
 *
 * @param view The {@link View} whose text should be returned.
 *
 * @return Speakable text derived from the {@link View} and its children. Returns an empty string
 *         if there is no such text, and {@code null} if {@code view == null}.
 */
static CharSequence getSpeakableTextForView(View view) {
    if (view == null) {
        return null;
    }

    View labelForThisView = ViewAccessibilityUtils.getLabelForView(view);
    if (labelForThisView != null) {
        return getSpeakableTextForView(labelForThisView);
    }

    SpannableStringBuilder returnStringBuilder = new SpannableStringBuilder("");

    // Accessibility importance is considered only on Jelly Bean and above
    if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
            || ViewAccessibilityUtils.isImportantForAccessibility(view)) {
        if (!TextUtils.isEmpty(view.getContentDescription())) {
            // contentDescription always wins out over other properties
            return view.getContentDescription();
        }
        if (view instanceof TextView) {
            if (!TextUtils.isEmpty(((TextView) view).getText())) {
                returnStringBuilder.append(((TextView) view).getText());
            } else if (!TextUtils.isEmpty(((TextView) view).getHint())) {
                returnStringBuilder.append(((TextView) view).getHint());
            }
        }
    }

    if (view instanceof ViewGroup) {
        ViewGroup group = (ViewGroup) view;
        // TODO(sjrush): Only evaluate child views if they're importantForAccessibility.
        for (int i = 0; i < group.getChildCount(); ++i) {
            View childView = group.getChildAt(i);
            if ((childView.getVisibility() == View.VISIBLE)
                    && !ViewAccessibilityUtils.isActionableForAccessibility(childView)) {
                returnStringBuilder.append(getSpeakableTextForView(childView));
            }
        }
    }

    if (view instanceof CompoundButton) {
        if (((CompoundButton) view).isChecked()) {
            StringBuilderUtils.appendWithSeparator(returnStringBuilder, "Checked");
        } else {
            StringBuilderUtils.appendWithSeparator(returnStringBuilder, "Not checked");
        }
    }
    return returnStringBuilder;
}

From source file:com.freshdigitable.udonroad.UserInfoView.java

private void bindURL(String displayUrl, String actualUrl) {
    if (TextUtils.isEmpty(displayUrl) || TextUtils.isEmpty(actualUrl)) {
        return;//from   w  ww.j  av a2 s  . c  om
    }
    final SpannableStringBuilder ssb = new SpannableStringBuilder(displayUrl);
    ssb.setSpan(new UnderlineSpan(), 0, displayUrl.length(), 0);
    url.setText(ssb);
    url.setVisibility(VISIBLE);
    urlIcon.setVisibility(VISIBLE);
    final OnClickListener clickListener = create(actualUrl);
    url.setOnClickListener(clickListener);
    urlIcon.setOnClickListener(clickListener);
}

From source file:com.collecdoo.fragment.main.RegisterDriverPhotoFragment.java

private void setColorSpan(TextView textView, int fromPos, int toPos) {
    SpannableStringBuilder sb = new SpannableStringBuilder(textView.getText());
    ForegroundColorSpan fcs = new ForegroundColorSpan(Color.RED);
    sb.setSpan(fcs, fromPos, toPos, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(sb);/*  w w w .  j av  a 2 s  .  c om*/
}

From source file:com.android.mms.ui.ConversationListItem.java

private CharSequence formatMessage() {
    final int color = android.R.styleable.Theme_textColorSecondary;
    String from = mConversation.getRecipients().formatNames(", ");
    if (MessageUtils.isWapPushNumber(from)) {
        String[] mAddresses = from.split(":");
        from = mAddresses[mContext.getResources().getInteger(R.integer.wap_push_address_index)];
    }//from w w  w  .  ja  va2s .co  m

    /**
     * Add boolean to know that the "from" haven't the Arabic and '+'.
     * Make sure the "from" display normally for RTL.
     */
    boolean isEnName = false;
    boolean isLayoutRtl = (TextUtils
            .getLayoutDirectionFromLocale(Locale.getDefault()) == View.LAYOUT_DIRECTION_RTL);
    if (isLayoutRtl && from != null) {
        if (from.length() >= 1) {
            Pattern pattern = Pattern.compile("[^-]+");
            Matcher matcher = pattern.matcher(from);
            isEnName = matcher.matches();
            if (isEnName && from.charAt(0) != '\u202D') {
                from = "\u202D" + from + "\u202C";
            }
        }
    }

    SpannableStringBuilder buf = new SpannableStringBuilder(from);

    if (mConversation.getMessageCount() > 1) {
        int before = buf.length();
        if (isLayoutRtl && isEnName) {
            buf.insert(1, mConversation.getMessageCount() + " ");
            buf.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.message_count_color)),
                    1, buf.length() - before, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        } else {
            buf.append(mContext.getResources().getString(R.string.message_count_format,
                    mConversation.getMessageCount()));
            buf.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.message_count_color)),
                    before, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        }
    }
    if (mConversation.hasDraft()) {
        if (isLayoutRtl && isEnName) {
            int before = buf.length();
            buf.insert(1, '\u202E' + mContext.getResources().getString(R.string.draft_separator) + '\u202C');
            buf.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.drawable.text_color_black)),
                    1, buf.length() - before + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            before = buf.length();
            int size;
            buf.insert(1, mContext.getResources().getString(R.string.has_draft));
            size = android.R.style.TextAppearance_Small;
            buf.setSpan(new TextAppearanceSpan(mContext, size), 1, buf.length() - before + 1,
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            buf.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.drawable.text_color_red)), 1,
                    buf.length() - before + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        } else {
            buf.append(mContext.getResources().getString(R.string.draft_separator));
            int before = buf.length();
            int size;
            buf.append(mContext.getResources().getString(R.string.has_draft));
            size = android.R.style.TextAppearance_Small;
            buf.setSpan(new TextAppearanceSpan(mContext, size, color), before, buf.length(),
                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            buf.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.drawable.text_color_red)),
                    before, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        }
    }

    // Unread messages are shown in bold
    if (mConversation.hasUnreadMessages()) {
        buf.setSpan(STYLE_BOLD, 0, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    return buf;
}