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.android.talkback.eventprocessor.ProcessorScreen.java

private CharSequence formatAnnouncementForArc(CharSequence title, boolean focusIntoArc) {
    SpannableStringBuilder builder = new SpannableStringBuilder(title);

    StringBuilderUtils.appendWithSeparator(builder, mService.getString(R.string.arc_android_window));

    if (focusIntoArc) {
        // Append short navigation hint.
        StringBuilderUtils.appendWithSeparator(builder, mService.getString(R.string.arc_navigation_hint));

        // Append hint to see the list of keyboard shortcuts.
        appendKeyboardShortcutHint(builder, R.string.arc_open_manage_keyboard_shortcuts_hint,
                R.string.keycombo_shortcut_open_manage_keyboard_shortcuts);

        // Append hint to open TalkBack settings.
        appendKeyboardShortcutHint(builder, R.string.arc_open_talkback_settings_hint,
                R.string.keycombo_shortcut_open_talkback_settings);
    }//from ww w  .  j  a va 2  s .  c  om

    return builder;
}

From source file:com.google.android.apps.iosched.util.UIUtils.java

/**
 * Given a snippet string with matching segments surrounded by curly
 * braces, turn those areas into bold spans, removing the curly braces.
 *///from   w  w w. j a  v a2 s  .  com
public static Spannable buildStyledSnippet(String snippet) {
    final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);

    // Walk through string, inserting bold snippet spans
    int startIndex = -1, endIndex = -1, delta = 0;
    while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {
        endIndex = snippet.indexOf('}', startIndex);

        // Remove braces from both sides
        builder.delete(startIndex - delta, startIndex - delta + 1);
        builder.delete(endIndex - delta - 1, endIndex - delta);

        // Insert bold style
        builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        delta += 2;
    }

    return builder;
}

From source file:io.github.hidroh.materialistic.data.HackerNewsItem.java

@Override
public Spannable getDisplayedTime(Context context) {
    if (displayedTime == null) {
        SpannableStringBuilder builder = new SpannableStringBuilder(
                dead ? context.getString(R.string.dead_prefix) + " " : "");
        SpannableString timeSpannable = new SpannableString(AppUtils.getAbbreviatedTimeSpan(time * 1000));
        if (deleted) {
            timeSpannable.setSpan(new StrikethroughSpan(), 0, timeSpannable.length(),
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }/*w  ww.  jav  a 2s .  c om*/
        builder.append(timeSpannable);
        displayedTime = builder;
    }
    return displayedTime;
}

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

private void displayHelp(CharSequence message) {
    cloneReadinessMessageView.setVisibility(message == null ? INVISIBLE : VISIBLE);
    if (message != null) {
        Editable spana = new SpannableStringBuilder(message);
        ClickableText.addLinks(spana, BOLD_LINK_STYLE, new ClickableText.Listener() {
            public void onClick(String command, View widget) {
                if (command.equals("specify_target_dir")) {
                    useDefaultGitDirLocationButton.setChecked(false);
                    gitDirEditText.requestFocus();
                    setCursorToEnd(gitDirEditText);
                } else if (command.equals("view_existing_repo")) {
                    startActivity(manageRepoIntent(existingRepoGitDir()));
                } else if (command.equals("view_ssh_instructions")) {
                    startActivity(new Intent(CloneLauncherActivity.this, AboutUsingSshActivity.class));
                } else if (command.equals("suggest_repo")) {
                    startActivityForResult(new GitIntentBuilder("repo.SUGGEST").toIntent(), 0);
                }/*from   w  w  w  . j a  va  2s  .  c o m*/
            }
        });
        cloneReadinessMessageView.setText(spana);
        cloneReadinessMessageView.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

From source file:com.example.activity.ProfileActivity.java

private void setPlayer() {
    ImageLoader.getInstance().displayImage(playerModel.player.avatar_url, head, BeeFrameworkApp.options_head);
    name.setText(playerModel.player.name);
    location.setText(playerModel.player.location);

    shots_count.setText(playerModel.player.shots_count + "");
    likes_count.setText(playerModel.player.likes_count + "");
    following_count.setText(playerModel.player.following_count + "");
    followers_count.setText(playerModel.player.followers_count + "");

    net.setText(playerModel.player.website_url);

    CharSequence text = net.getText();
    if (text instanceof Spannable) {
        int end = text.length();
        Spannable sp = (Spannable) net.getText();
        URLSpan[] spans = sp.getSpans(0, end, URLSpan.class);
        SpannableStringBuilder style = new SpannableStringBuilder(text);
        style.clearSpans();// should clear old spans
        for (URLSpan span : spans) {
            JayceSpan mySpan = new JayceSpan(span.getURL());
            style.setSpan(mySpan, sp.getSpanStart(span), sp.getSpanEnd(span),
                    Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }/* ww w .ja  v a  2 s  . c  om*/
        net.setText(style);
    }
}

From source file:org.telegram.ui.GroupCreateActivity.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (fragmentView == null) {
        fragmentView = inflater.inflate(R.layout.group_create_layout, container, false);

        epmtyTextView = (TextView) fragmentView.findViewById(R.id.searchEmptyView);
        userSelectEditText = (EditText) fragmentView.findViewById(R.id.bubble_input_text);
        countTextView = (TextView) fragmentView.findViewById(R.id.bubble_counter_text);
        if (Build.VERSION.SDK_INT >= 11) {
            userSelectEditText.setTextIsSelectable(false);
        }//from w w  w.  j a  va 2s  . c om
        userSelectEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
                if (!ignoreChange) {
                    beforeChangeIndex = userSelectEditText.getSelectionStart();
                    changeString = new SpannableString(charSequence);
                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!ignoreChange) {
                    boolean search = false;
                    int afterChangeIndex = userSelectEditText.getSelectionEnd();
                    if (editable.toString().length() < changeString.toString().length()) {
                        String deletedString = "";
                        try {
                            deletedString = changeString.toString().substring(afterChangeIndex,
                                    beforeChangeIndex);
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                        if (deletedString.length() > 0) {
                            if (searching && searchWas) {
                                search = true;
                            }
                            Spannable span = userSelectEditText.getText();
                            for (int a = 0; a < allSpans.size(); a++) {
                                Emoji.XImageSpan sp = allSpans.get(a);
                                if (span.getSpanStart(sp) == -1) {
                                    allSpans.remove(sp);
                                    selectedContacts.remove(sp.uid);
                                }
                            }
                            if (selectedContacts.isEmpty()) {
                                doneTextView.setText(getStringEntry(R.string.Done));
                            } else {
                                doneTextView.setText(
                                        getStringEntry(R.string.Done) + " (" + selectedContacts.size() + ")");
                            }
                            countTextView.setText(selectedContacts.size() + "/200");
                            listView.invalidateViews();
                        } else {
                            search = true;
                        }
                    } else {
                        search = true;
                    }
                    if (search) {
                        String text = userSelectEditText.getText().toString().replace("<", "");
                        if (text.length() != 0) {
                            searchDialogs(text);
                            searching = true;
                            searchWas = true;
                            epmtyTextView.setText(getStringEntry(R.string.NoResult));
                            listViewAdapter.notifyDataSetChanged();
                        } else {
                            searchResult = null;
                            searchResultNames = null;
                            searching = false;
                            searchWas = false;
                            epmtyTextView.setText(getStringEntry(R.string.NoContacts));
                            listViewAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });

        listView = (PinnedHeaderListView) fragmentView.findViewById(R.id.listView);
        listView.setEmptyView(epmtyTextView);
        listView.setVerticalScrollBarEnabled(false);

        listView.setAdapter(listViewAdapter = new ListAdapter(parentActivity));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TLRPC.User user;
                int section = listViewAdapter.getSectionForPosition(i);
                int row = listViewAdapter.getPositionInSectionForPosition(i);
                if (searching && searchWas) {
                    user = searchResult.get(row);
                } else {
                    ArrayList<TLRPC.TL_contact> arr = ContactsController.Instance.usersSectionsDict
                            .get(ContactsController.Instance.sortedUsersSectionsArray.get(section));
                    user = MessagesController.Instance.users.get(arr.get(row).user_id);
                    listView.invalidateViews();
                }
                if (selectedContacts.containsKey(user.id)) {
                    Emoji.XImageSpan span = selectedContacts.get(user.id);
                    selectedContacts.remove(user.id);
                    SpannableStringBuilder text = new SpannableStringBuilder(userSelectEditText.getText());
                    text.delete(text.getSpanStart(span), text.getSpanEnd(span));
                    allSpans.remove(span);
                    ignoreChange = true;
                    userSelectEditText.setText(text);
                    userSelectEditText.setSelection(text.length());
                    ignoreChange = false;
                } else {
                    if (selectedContacts.size() == 200) {
                        return;
                    }
                    ignoreChange = true;
                    Emoji.XImageSpan span = createAndPutChipForUser(user);
                    span.uid = user.id;
                    ignoreChange = false;
                }
                if (selectedContacts.isEmpty()) {
                    doneTextView.setText(getStringEntry(R.string.Done));
                } else {
                    doneTextView.setText(getStringEntry(R.string.Done) + " (" + selectedContacts.size() + ")");
                }
                countTextView.setText(selectedContacts.size() + "/200");
                if (searching || searchWas) {
                    searching = false;
                    searchWas = false;
                    epmtyTextView.setText(getStringEntry(R.string.NoContacts));

                    ignoreChange = true;
                    SpannableStringBuilder ssb = new SpannableStringBuilder("");
                    for (ImageSpan sp : allSpans) {
                        ssb.append("<<");
                        ssb.setSpan(sp, ssb.length() - 2, ssb.length(),
                                SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                    userSelectEditText.setText(ssb);
                    userSelectEditText.setSelection(ssb.length());
                    ignoreChange = false;

                    listViewAdapter.notifyDataSetChanged();
                } else {
                    listView.invalidateViews();
                }
            }
        });
    } else {
        ViewGroup parent = (ViewGroup) fragmentView.getParent();
        if (parent != null) {
            parent.removeView(fragmentView);
        }
    }
    return fragmentView;
}

From source file:com.yahala.ui.GroupCreateActivity.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (fragmentView == null) {

        searching = false;/*from  www  . j  av a  2 s .c o  m*/
        searchWas = false;

        fragmentView = inflater.inflate(R.layout.group_create_layout, container, false);

        emptyTextView = (TextView) fragmentView.findViewById(R.id.searchEmptyView);
        emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
        userSelectEditText = (EditText) fragmentView.findViewById(R.id.bubble_input_text);
        userSelectEditText.setHint(LocaleController.getString("SendMessageTo", R.string.SendMessageTo));
        if (Build.VERSION.SDK_INT >= 11) {
            userSelectEditText.setTextIsSelectable(false);
        }
        userSelectEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
                if (!ignoreChange) {
                    beforeChangeIndex = userSelectEditText.getSelectionStart();
                    changeString = new SpannableString(charSequence);
                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!ignoreChange) {
                    boolean search = false;
                    int afterChangeIndex = userSelectEditText.getSelectionEnd();
                    if (editable.toString().length() < changeString.toString().length()) {
                        String deletedString = "";
                        try {
                            deletedString = changeString.toString().substring(afterChangeIndex,
                                    beforeChangeIndex);
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                        if (deletedString.length() > 0) {
                            if (searching && searchWas) {
                                search = true;
                            }
                            Spannable span = userSelectEditText.getText();
                            for (int a = 0; a < allSpans.size(); a++) {
                                XImageSpan sp = allSpans.get(a);
                                if (span.getSpanStart(sp) == -1) {
                                    allSpans.remove(sp);
                                    selectedContacts.remove(sp.jid);
                                }
                            }
                            if (parentActivity != null) {
                                ActionBar actionBar = parentActivity.getSupportActionBar();
                                actionBar.setSubtitle(String.format("%d/200 %s", selectedContacts.size(),
                                        LocaleController.getString("Members", R.string.Members)));
                            }
                            listView.invalidateViews();
                        } else {
                            search = true;
                        }
                    } else {
                        search = true;
                    }
                    if (search) {
                        String text = userSelectEditText.getText().toString().replace("<", "");
                        if (text.length() != 0) {
                            searchDialogs(text);
                            searching = true;
                            searchWas = true;
                            emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult));
                            listViewAdapter.notifyDataSetChanged();
                        } else {
                            searchResult = null;
                            searchResultNames = null;
                            searching = false;
                            searchWas = false;
                            emptyTextView
                                    .setText(LocaleController.getString("NoContacts", R.string.NoContacts));
                            listViewAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });

        listView = (PinnedHeaderListView) fragmentView.findViewById(R.id.listView);
        listView.setEmptyView(emptyTextView);
        listView.setVerticalScrollBarEnabled(false);

        listView.setAdapter(listViewAdapter = new ListAdapter(parentActivity));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TLRPC.User user;
                int section = listViewAdapter.getSectionForPosition(i);
                int row = listViewAdapter.getPositionInSectionForPosition(i);
                if (searching && searchWas) {
                    user = searchResult.get(row);
                } else {
                    ArrayList<TLRPC.User> arr = com.yahala.xmpp.ContactsController
                            .getInstance().usersSectionsDict.get(
                                    com.yahala.xmpp.ContactsController.getInstance().sortedUsersSectionsArray
                                            .get(section));
                    user = com.yahala.xmpp.ContactsController.getInstance().friendsDict.get(arr.get(row).jid);
                    listView.invalidateViews();
                }
                if (selectedContacts.containsKey(user.jid)) {
                    XImageSpan span = selectedContacts.get(user.jid);
                    selectedContacts.remove(user.jid);
                    SpannableStringBuilder text = new SpannableStringBuilder(userSelectEditText.getText());
                    text.delete(text.getSpanStart(span), text.getSpanEnd(span));
                    allSpans.remove(span);
                    ignoreChange = true;
                    userSelectEditText.setText(text);
                    userSelectEditText.setSelection(text.length());
                    ignoreChange = false;
                } else {
                    if (selectedContacts.size() == 200) {
                        return;
                    }
                    ignoreChange = true;
                    XImageSpan span = createAndPutChipForUser(user);
                    span.jid = user.jid;
                    ignoreChange = false;
                }
                if (parentActivity != null) {
                    ActionBar actionBar = parentActivity.getSupportActionBar();
                    actionBar.setSubtitle(String.format("%d/200 %s", selectedContacts.size(),
                            LocaleController.getString("Members", R.string.Members)));
                }
                if (searching || searchWas) {
                    searching = false;
                    searchWas = false;
                    emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));

                    ignoreChange = true;
                    SpannableStringBuilder ssb = new SpannableStringBuilder("");
                    for (ImageSpan sp : allSpans) {
                        ssb.append("<<");
                        ssb.setSpan(sp, ssb.length() - 2, ssb.length(),
                                SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                    userSelectEditText.setText(ssb);
                    userSelectEditText.setSelection(ssb.length());
                    ignoreChange = false;

                    listViewAdapter.notifyDataSetChanged();
                } else {
                    listView.invalidateViews();
                }
            }
        });
    } else {
        ViewGroup parent = (ViewGroup) fragmentView.getParent();
        if (parent != null) {
            parent.removeView(fragmentView);
        }
    }
    return fragmentView;
}

From source file:com.vuze.android.remote.spanbubbles.SpanTags.java

public void updateTags() {
    StringBuilder sb = buildSpannableString();
    SpannableStringBuilder ss = new SpannableStringBuilder(sb);

    String string = sb.toString();

    setTagBubbles(ss, string, "~!~");

    if (flipper != null) {
        flipper.changeText(tvTags, ss, false, validator);
        return;/*from   ww w.j a  va 2  s . c  o m*/
    }

    if (!string.equals(tvTags.getText().toString())) {
        //         int start = tvTags.getSelectionStart();
        //         int end = tvTags.getSelectionEnd();
        //         Log.e(TAG, "Selection " + tvTags.getSelectionStart() + " to " +
        //               tvTags.getSelectionEnd());
        tvTags.setTextKeepState(ss);
        //CharSequence so = tvTags.getText();
        //Selection.getSelectionStart(so);
        //         if (start >= 0 && end >= 0) {
        //            Selection.setSelection(ss, start, end);
        //         }
        //         tvTags.setText(ss);
        //         if (start >= 0 && end >= 0) {
        //            Selection.setSelection((Spannable) tvTags.getText(), start, end);
        //         }
    }
}

From source file:com.viewpagerindicator.TabTextPageIndicator.java

/**
 * textview//from  w  w  w .ja  v  a  2s.  c  o  m
 *
 * @param textView
 */
private void setTextColor(TextView textView) {
    if (textView == null) {
        return;
    }
    String textString = textView.getText().toString();
    if (textString.isEmpty()) {
        return;
    }
    int start = textString.indexOf("(");
    int end = textString.indexOf(")");
    if (start < 0 || end < 0 || end < start) {
        return;
    }
    SpannableStringBuilder builder = new SpannableStringBuilder(textString);
    // ForegroundColorSpan ?BackgroundColorSpan
    ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.parseColor("#39a5ec"));
    builder.setSpan(redSpan, start, end + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    // ?
    builder.setSpan(new MyStyleSpan(Typeface.NORMAL), start, end + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    textView.setText(builder);
}

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

public final void bind(Context context, final Conversation conversation) {
    //if (DEBUG) Log.v(TAG, "bind()");
    boolean sameItem = mConversation != null && mConversation.getThreadId() == conversation.getThreadId();

    mConversation = conversation;// ww  w  . j a v  a2s  .  c o m

    LayoutParams attachmentLayout = (LayoutParams) mAttachmentView.getLayoutParams();
    boolean hasError = conversation.hasError();
    // When there's an error icon, the attachment icon is left of the error icon.
    // When there is not an error icon, the attachment icon is left of the date text.
    // As far as I know, there's no way to specify that relationship in xml.
    if (hasError) {
        attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.error);
    } else {
        attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.date);
    }

    boolean hasAttachment = conversation.hasAttachment();
    mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE);

    // Date
    mDateView.setText(MessageUtils.formatTimeStampString(context, conversation.getDate()));

    // From.
    mFromView.setText(formatMessage());

    // Register for updates in changes of any of the contacts in this conversation.
    ContactList contacts = conversation.getRecipients();

    if (Log.isLoggable(LogTag.CONTACT, Log.DEBUG)) {
        Log.v(TAG, "bind: contacts.addListeners " + this);
    }
    Contact.addListener(this);

    // Subject
    SmileyParser parser = SmileyParser.getInstance();
    final String snippet = conversation.getSnippet();
    if (mConversation.hasUnreadMessages()) {
        SpannableStringBuilder buf = new SpannableStringBuilder(parser.addSmileySpans(snippet));
        buf.setSpan(STYLE_BOLD, 0, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        mSubjectView.setText(buf);
    } else {
        mSubjectView.setText(parser.addSmileySpans(snippet));
    }

    // Transmission error indicator.
    mErrorIndicator.setVisibility(hasError ? VISIBLE : GONE);

    updateAvatarView();
    mAvatarView.setChecked(isChecked(), sameItem);
}