Example usage for android.text SpannableStringBuilder insert

List of usage examples for android.text SpannableStringBuilder insert

Introduction

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

Prototype

public SpannableStringBuilder insert(int where, CharSequence tb) 

Source Link

Usage

From source file:Main.java

public static Spannable applyKerning(CharSequence src, float kerning, int start, int end) {
    if (src == null)
        return null;
    final int srcLength = src.length();
    if (srcLength < 2)
        return src instanceof Spannable ? (Spannable) src : new SpannableString(src);
    if (start < 0)
        start = 0;//w  w w. j  a  v a  2 s .c o m
    if (end > srcLength)
        end = srcLength;

    final String nonBreakingSpace = "\u00A0";
    final SpannableStringBuilder builder = src instanceof SpannableStringBuilder ? (SpannableStringBuilder) src
            : new SpannableStringBuilder(src);
    for (int i = src.length(); i >= 1; i--) {
        builder.insert(i, nonBreakingSpace);
        builder.setSpan(new ScaleXSpan(kerning), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    return builder;
}

From source file:org.mozilla.gecko.home.ReadingListPanel.java

private void updateUiFromCursor(Cursor c) {
    // We delay setting the empty view until the cursor is actually empty.
    // This avoids image flashing.
    if ((c == null || c.getCount() == 0) && mEmptyView == null) {
        final ViewStub emptyViewStub = (ViewStub) mTopView.findViewById(R.id.home_empty_view_stub);
        mEmptyView = emptyViewStub.inflate();

        final TextView emptyHint = (TextView) mEmptyView.findViewById(R.id.home_empty_hint);
        if (HardwareUtils.isLowMemoryPlatform()) {
            emptyHint.setVisibility(View.GONE);
        } else {//w w w  .j a v a2  s. c om
            String readingListHint = emptyHint.getText().toString();

            // Use an ImageSpan to include the reader icon in the "Tip".
            int imageSpanIndex = readingListHint.indexOf(MATCH_STRING);
            if (imageSpanIndex != -1) {
                final ImageSpan readingListIcon = new ImageSpan(getActivity(), R.drawable.reader_cropped,
                        ImageSpan.ALIGN_BOTTOM);
                final SpannableStringBuilder hintBuilder = new SpannableStringBuilder(readingListHint);

                // Add additional spacing.
                hintBuilder.insert(imageSpanIndex + MATCH_STRING.length(), " ");
                hintBuilder.insert(imageSpanIndex, " ");

                // Add icon.
                hintBuilder.setSpan(readingListIcon, imageSpanIndex + 1,
                        imageSpanIndex + MATCH_STRING.length() + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

                emptyHint.setText(hintBuilder, TextView.BufferType.SPANNABLE);
            }
        }

        mList.setEmptyView(mEmptyView);
    }
}

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 v  a2s .  c o  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;
}

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

/**
 * Formats some braille content from an {@link AccessibilityNodeInfoCompat}.
 * Marks the description with a cursor right after the last character
 * matching the search query. Returns content with keep pan strategy
 * by default, or reset pan strategy if there is no matched node stored yet.
 *///from w w  w. j av a 2  s. c o  m
private DisplayManager.Content formatNodeToBraille(AccessibilityNodeInfoCompat node) {
    if (node == null) {
        return null;
    }
    DisplayManager.Content content = mNodeBrailler.brailleNode(node);
    if (content == null) {
        return null;
    }

    Spanned spanned = content.getSpanned();
    if (spanned == null) {
        LogUtils.log(this, Log.ERROR, "No text for node");
        return null;
    }

    // Find index of match and the index corresponding to the
    // end of the matched text so we know where to place the cursor.
    String lowerCase = spanned.toString().toLowerCase();
    String matchText = mQueryText.toString().toLowerCase();
    AccessibilityNodeInfoCompat spanNode = (AccessibilityNodeInfoCompat) DisplaySpans.getEqualSpan(spanned,
            node);
    int cursorIndex = -1;
    if (spanNode != null) {
        int nodeIndex = spanned.getSpanStart(spanNode);
        if (nodeIndex >= 0 && nodeIndex < lowerCase.length()) {
            int matchIndex = lowerCase.indexOf(matchText, nodeIndex);
            if (matchIndex >= 0 && matchIndex <= lowerCase.length()) {
                cursorIndex = matchIndex + matchText.length();
            }
        }
    }

    // Add prefix to what's displayed to mark this as a search result.
    String prefix = mAccessibilityService.getString(R.string.search_result_prefix);
    int lengthDiff = prefix.length();
    SpannableStringBuilder sb = (SpannableStringBuilder) spanned;
    sb.insert(0, prefix);

    // If match in this node, add cursor at end of match.
    if (cursorIndex != -1) {
        DisplaySpans.addSelection(sb, cursorIndex + lengthDiff, cursorIndex + lengthDiff);
    }

    // No matched node stored, means we have just activated search mode,
    // so we want to reset the panning frame so we can see the search
    // prefix.
    int panStrategy = AccessibilityNodeInfoRef.isNull(mMatchedNode) ? DisplayManager.Content.PAN_RESET
            : DisplayManager.Content.PAN_KEEP;

    return content.setPanStrategy(panStrategy);
}

From source file:org.hopestarter.wallet.ui.send.SweepWalletFragment.java

private void updateView() {
    final MonetaryFormat btcFormat = config.getFormat();

    if (walletToSweep != null) {
        balanceView.setVisibility(View.VISIBLE);
        final MonetarySpannable balanceSpannable = new MonetarySpannable(btcFormat,
                walletToSweep.getBalance(BalanceType.ESTIMATED));
        balanceSpannable.applyMarkup(null, null);
        final SpannableStringBuilder balance = new SpannableStringBuilder(balanceSpannable);
        balance.insert(0, ": ");
        balance.insert(0, getString(R.string.sweep_wallet_fragment_balance));
        balanceView.setText(balance);//from w w w  .j  a  v  a 2s . c om
    } else {
        balanceView.setVisibility(View.GONE);
    }

    if (state == State.DECODE_KEY && privateKeyToSweep == null) {
        messageView.setVisibility(View.VISIBLE);
        messageView.setText(R.string.sweep_wallet_fragment_wallet_unknown);
    } else if (state == State.DECODE_KEY && privateKeyToSweep != null) {
        messageView.setVisibility(View.VISIBLE);
        messageView.setText(R.string.sweep_wallet_fragment_encrypted);
    } else if (privateKeyToSweep != null) {
        messageView.setVisibility(View.GONE);
    }

    passwordViewGroup
            .setVisibility(state == State.DECODE_KEY && privateKeyToSweep != null ? View.VISIBLE : View.GONE);

    hintView.setVisibility(state == State.DECODE_KEY && privateKeyToSweep == null ? View.VISIBLE : View.GONE);

    if (sentTransaction != null) {
        sweepTransactionView.setVisibility(View.VISIBLE);
        sweepTransactionAdapter.setFormat(btcFormat);
        sweepTransactionAdapter.replace(sentTransaction);
        sweepTransactionAdapter.bindViewHolder(sweepTransactionViewHolder, 0);
    } else {
        sweepTransactionView.setVisibility(View.GONE);
    }

    if (state == State.DECODE_KEY) {
        viewCancel.setText(R.string.button_cancel);
        viewGo.setText(R.string.sweep_wallet_fragment_button_decrypt);
        viewGo.setEnabled(privateKeyToSweep != null);
    } else if (state == State.CONFIRM_SWEEP) {
        viewCancel.setText(R.string.button_cancel);
        viewGo.setText(R.string.sweep_wallet_fragment_button_sweep);
        viewGo.setEnabled(
                walletToSweep != null && walletToSweep.getBalance(BalanceType.ESTIMATED).signum() > 0);
    } else if (state == State.PREPARATION) {
        viewCancel.setText(R.string.button_cancel);
        viewGo.setText(R.string.send_coins_preparation_msg);
        viewGo.setEnabled(false);
    } else if (state == State.SENDING) {
        viewCancel.setText(R.string.send_coins_fragment_button_back);
        viewGo.setText(R.string.send_coins_sending_msg);
        viewGo.setEnabled(false);
    } else if (state == State.SENT) {
        viewCancel.setText(R.string.send_coins_fragment_button_back);
        viewGo.setText(R.string.send_coins_sent_msg);
        viewGo.setEnabled(false);
    } else if (state == State.FAILED) {
        viewCancel.setText(R.string.send_coins_fragment_button_back);
        viewGo.setText(R.string.send_coins_failed_msg);
        viewGo.setEnabled(false);
    }

    viewCancel.setEnabled(state != State.PREPARATION);

    // enable actions
    if (reloadAction != null)
        reloadAction.setEnabled(state == State.CONFIRM_SWEEP && walletToSweep != null);
    if (scanAction != null)
        scanAction.setEnabled(state == State.DECODE_KEY || state == State.CONFIRM_SWEEP);
}

From source file:org.solovyev.android.calculator.widget.CalculatorWidget.java

private void updateEditorState(@Nonnull Context context, @Nonnull RemoteViews views, @Nonnull EditorState state,
        @Nonnull SimpleTheme theme) {//from  ww  w. ja  v  a  2s  .c o  m
    final boolean unspan = App.getTheme().light != theme.light;

    final CharSequence text = state.text;
    final int selection = state.selection;
    if (selection < 0 || selection > text.length()) {
        views.setTextViewText(R.id.calculator_editor, unspan ? App.unspan(text) : text);
        return;
    }

    final SpannableStringBuilder result;
    // inject cursor
    if (unspan) {
        final CharSequence beforeCursor = text.subSequence(0, selection);
        final CharSequence afterCursor = text.subSequence(selection, text.length());

        result = new SpannableStringBuilder();
        result.append(App.unspan(beforeCursor));
        result.append(getCursorString(context));
        result.append(App.unspan(afterCursor));
    } else {
        result = new SpannableStringBuilder(text);
        result.insert(selection, getCursorString(context));
    }
    views.setTextViewText(R.id.calculator_editor, result);
}

From source file:net.kourlas.voipms_sms.adapters.ConversationsRecyclerViewAdapter.java

@Override
public void onBindViewHolder(ConversationViewHolder conversationViewHolder, int position) {
    Message message = messages.get(position);

    ViewSwitcher viewSwitcher = conversationViewHolder.getViewSwitcher();
    viewSwitcher.setDisplayedChild(isItemChecked(position) ? 1 : 0);

    QuickContactBadge contactBadge = conversationViewHolder.getContactBadge();
    contactBadge.assignContactFromPhone(message.getContact(), true);

    String photoUri = Utils.getContactPhotoUri(applicationContext, message.getContact());
    if (photoUri != null) {
        contactBadge.setImageURI(Uri.parse(photoUri));
    } else {/*from w  w w. ja  v  a  2 s  . c o  m*/
        contactBadge.setImageToDefault();
    }

    TextView contactTextView = conversationViewHolder.getContactTextView();
    String contactName = Utils.getContactName(applicationContext, message.getContact());
    SpannableStringBuilder contactTextBuilder = new SpannableStringBuilder();
    if (contactName != null) {
        contactTextBuilder.append(contactName);
    } else {
        contactTextBuilder.append(Utils.getFormattedPhoneNumber(message.getContact()));
    }
    if (!filterConstraint.equals("")) {
        int index = contactTextBuilder.toString().toLowerCase().indexOf(filterConstraint.toLowerCase());
        if (index != -1) {
            contactTextBuilder.setSpan(
                    new BackgroundColorSpan(ContextCompat.getColor(applicationContext, R.color.highlight)),
                    index, index + filterConstraint.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        }
    }
    contactTextView.setText(contactTextBuilder);

    final TextView messageTextView = conversationViewHolder.getMessageTextView();
    SpannableStringBuilder messageTextBuilder = new SpannableStringBuilder();

    int index = message.getText().toLowerCase().indexOf(filterConstraint.toLowerCase());
    if (!filterConstraint.equals("") && index != -1) {
        int nonMessageOffset = index;
        if (message.getType() == Message.Type.OUTGOING) {
            messageTextBuilder.insert(0,
                    applicationContext.getString(R.string.conversations_message_you) + " ");
            nonMessageOffset += 5;
        }

        int substringOffset = index - 20;
        if (substringOffset > 0) {
            messageTextBuilder.append("...");
            nonMessageOffset += 3;

            while (message.getText().charAt(substringOffset) != ' ' && substringOffset < index - 1) {
                substringOffset += 1;
            }
            substringOffset += 1;
        } else {
            substringOffset = 0;
        }

        messageTextBuilder.append(message.getText().substring(substringOffset));
        messageTextBuilder.setSpan(
                new BackgroundColorSpan(ContextCompat.getColor(applicationContext, R.color.highlight)),
                nonMessageOffset - substringOffset,
                nonMessageOffset - substringOffset + filterConstraint.length(),
                SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
    } else {
        if (message.getType() == Message.Type.OUTGOING) {
            messageTextBuilder.append(applicationContext.getString(R.string.conversations_message_you));
            messageTextBuilder.append(" ");
        }
        messageTextBuilder.append(message.getText());
    }
    messageTextView.setText(messageTextBuilder);

    if (message.isUnread()) {
        contactTextView.setTypeface(null, Typeface.BOLD);
        messageTextView.setTypeface(null, Typeface.BOLD);
    } else {
        contactTextView.setTypeface(null, Typeface.NORMAL);
        messageTextView.setTypeface(null, Typeface.NORMAL);
    }

    // Set date line
    TextView dateTextView = conversationViewHolder.getDateTextView();
    if (message.isDraft()) {
        SpannableStringBuilder dateTextBuilder = new SpannableStringBuilder();
        dateTextBuilder.append(applicationContext.getString(R.string.conversations_message_draft));
        dateTextBuilder.setSpan(new StyleSpan(Typeface.ITALIC), 0, dateTextBuilder.length(),
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        dateTextView.setText(dateTextBuilder);
    } else if (!message.isDelivered()) {
        if (!message.isDeliveryInProgress()) {
            SpannableStringBuilder dateTextBuilder = new SpannableStringBuilder();
            dateTextBuilder.append(applicationContext.getString(R.string.conversations_message_not_sent));
            dateTextBuilder.setSpan(
                    new ForegroundColorSpan(
                            ContextCompat.getColor(applicationContext, android.R.color.holo_red_dark)),
                    0, dateTextBuilder.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            dateTextView.setText(dateTextBuilder);
        } else {
            dateTextView.setText(applicationContext.getString(R.string.conversations_message_sending));
        }
    } else {
        dateTextView.setText(Utils.getFormattedDate(applicationContext, message.getDate(), true));
    }
}

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

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    int count = mAdapter.getCount();
    if (position > count) {
        if (isreload) {
            mFootview.findViewById(R.id.list_footview_progress).setVisibility(View.VISIBLE);
            TextView textview = (TextView) mFootview.findViewById(R.id.list_footview_text);
            textview.setText(R.string.buffering);
            requestData(pageIndex, false);
        }/*from  ww  w.  ja va  2s . co m*/
        return;
    }
    //        showBar(); //TODO: show input bar when selected comment
    Object o = parent.getItemAtPosition(position);
    if (o == null || !(o instanceof Comment))
        return;
    Comment c = (Comment) o;
    int quoteCount = getQuoteCount();
    removeQuote(mCommentText.getText());
    if (quoteCount == c.count)
        return; // ?
    String pre = ":#" + c.count;
    mQuoteSpan = new Quote(c.count);
    SpannableStringBuilder sb = SpannableStringBuilder.valueOf(mCommentText.getText());
    TextView tv = TextViewUtils.createBubbleTextView(this, pre);
    BitmapDrawable bd = (BitmapDrawable) TextViewUtils.convertViewToDrawable(tv);
    bd.setBounds(0, 0, bd.getIntrinsicWidth(), bd.getIntrinsicHeight());
    sb.insert(0, pre);
    mQuoteImage = new ImageSpan(bd);
    sb.setSpan(mQuoteImage, 0, pre.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(mQuoteSpan, 0, pre.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.append("");
    mCommentText.setText(sb);
    mCommentText.setSelection(mCommentText.getText().length());
}

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

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    int count = mAdapter.getCount();
    if (position > count) {
        if (isreload) {
            mFootview.findViewById(R.id.list_footview_progress).setVisibility(View.VISIBLE);
            TextView textview = (TextView) mFootview.findViewById(R.id.list_footview_text);
            textview.setText(R.string.loading);
            requestData(pageIndex, false);
        }/*w  w w.  j a v a2  s . co  m*/
        return;
    }
    showBar(); // show input bar when selected comment
    Object o = parent.getItemAtPosition(position);
    if (o == null || !(o instanceof Comment))
        return;
    Comment c = (Comment) o;
    int quoteCount = getQuoteCount();
    removeQuote(mCommentText.getText());
    if (quoteCount == c.count)
        return; // ?
    String pre = ":#" + c.count;
    mQuoteSpan = new Quote(c.count);
    /**
     * @see http 
     *      ://www.kpbird.com/2013/02/android-chips-edittext-token-edittext
     *      .html
     */
    SpannableStringBuilder sb = SpannableStringBuilder.valueOf(mCommentText.getText());
    TextView tv = TextViewUtils.createBubbleTextView(this, pre);
    BitmapDrawable bd = (BitmapDrawable) TextViewUtils.convertViewToDrawable(tv);
    bd.setBounds(0, 0, bd.getIntrinsicWidth(), bd.getIntrinsicHeight());
    sb.insert(0, pre);
    mQuoteImage = new ImageSpan(bd);
    sb.setSpan(mQuoteImage, 0, pre.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(mQuoteSpan, 0, pre.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.append("");
    mCommentText.setText(sb);
    mCommentText.setSelection(mCommentText.getText().length());
}

From source file:cgeo.geocaching.CacheDetailActivity.java

static void updateCacheLists(final View view, final Geocache cache, final Resources res) {
    final SpannableStringBuilder builder = new SpannableStringBuilder();
    for (final Integer listId : cache.getLists()) {
        if (builder.length() > 0) {
            builder.append(", ");
        }//from   www .  j  a  v a2  s.c  om
        appendClickableList(builder, view, listId);
    }
    builder.insert(0, res.getString(R.string.list_list_headline) + " ");
    final TextView offlineLists = ButterKnife.findById(view, R.id.offline_lists);
    offlineLists.setText(builder);
    offlineLists.setMovementMethod(LinkMovementMethod.getInstance());
}