Example usage for android.text SpannableStringBuilder setSpan

List of usage examples for android.text SpannableStringBuilder setSpan

Introduction

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

Prototype

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

Source Link

Document

Mark the specified range of text with the specified object.

Usage

From source file:com.goliathonline.android.kegbot.ui.DrinkDetailFragment.java

/**
 * Handle {@link SessionsQuery} {@link Cursor}.
 *//* w ww .  j  a v  a2  s .c om*/
private void onDrinkQueryComplete(Cursor cursor) {
    try {
        mSessionCursor = true;
        if (!cursor.moveToFirst()) {
            return;
        }

        // Format time block this session occupies
        //final long blockStart = cursor.getLong(DrinksQuery.BLOCK_START);
        //final long blockEnd = cursor.getLong(DrinksQuery.BLOCK_END);
        //final String roomName = cursor.getString(DrinksQuery.ROOM_NAME);
        //final String subtitle = UIUtils.formatSessionSubtitle(blockStart,
        //        blockEnd, roomName, getActivity());

        mTitleString = "Drink " + cursor.getString(DrinksQuery.DRINK_ID);
        mTitle.setText(mTitleString);
        String userId = cursor.getString(DrinksQuery.USER_ID);
        if (TextUtils.isEmpty(userId))
            userId = "guest";
        mSubtitle.setText(userId);

        //mUrl = cursor.getString(DrinksQuery.URL);
        if (TextUtils.isEmpty(mUrl)) {
            mUrl = "";
        }

        //mHashtag = cursor.getString(DrinksQuery.HASHTAG);
        mTagDisplay = (TextView) mRootView.findViewById(R.id.session_tags_button);
        if (!TextUtils.isEmpty(mHashtag)) {
            // Create the button text
            SpannableStringBuilder sb = new SpannableStringBuilder();
            sb.append(getString(R.string.tag_stream) + " ");
            int boldStart = sb.length();
            sb.append(getHashtagsString());
            sb.setSpan(sBoldSpan, boldStart, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            mTagDisplay.setText(sb);

            mTagDisplay.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), TagStreamActivity.class);
                    intent.putExtra(TagStreamFragment.EXTRA_QUERY, getHashtagsString());
                    startActivity(intent);
                }
            });
        } else {
            mTagDisplay.setVisibility(View.GONE);
        }

        //mRoomId = cursor.getString(DrinksQuery.ROOM_ID);

        // Unregister around setting checked state to avoid triggering
        // listener since change isn't user generated.
        mStarred.setOnCheckedChangeListener(null);
        mStarred.setChecked(cursor.getInt(DrinksQuery.STARRED) != 0);
        mStarred.setOnCheckedChangeListener(this);

        final String sessionAbstract = ""; //cursor.getString(DrinksQuery.ABSTRACT);
        if (!TextUtils.isEmpty(sessionAbstract)) {
            UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract);
            mAbstract.setVisibility(View.VISIBLE);
            mHasSummaryContent = true;
        } else {
            mAbstract.setVisibility(View.GONE);
        }

        final View requirementsBlock = mRootView.findViewById(R.id.drink_pour_block);
        final String sessionRequirements = UnitUtils.mlToOz(cursor.getString(DrinksQuery.VOLUME)) + "oz";
        if (!TextUtils.isEmpty(sessionRequirements)) {
            UIUtils.setTextMaybeHtml(mRequirements, sessionRequirements);
            requirementsBlock.setVisibility(View.VISIBLE);
            mHasSummaryContent = true;
        } else {
            requirementsBlock.setVisibility(View.GONE);
        }

        // Show empty message when all data is loaded, and nothing to show
        if (mSpeakersCursor && !mHasSummaryContent) {
            mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
        }

        AnalyticsUtils.getInstance(getActivity()).trackPageView("/Drinks/" + mTitleString);

        updateLinksTab(cursor);
        updateNotesTab();

    } finally {
        cursor.close();
    }
}

From source file:com.heath_bar.tvdb.SeriesOverview.java

private SpannableStringBuilder tagsBuilder(String text, String delim) {
    SpannableStringBuilder builtTags = new SpannableStringBuilder();
    int start = 0;
    int end = 0;// ww w  .  j  a  v  a  2 s.com

    // if no text, break early
    if (text.length() == 0)
        return builtTags;

    // If the string starts with delim, remove the first delim
    if (text.substring(0, 1).equals(delim))
        text = text.substring(1);

    do {
        start = 0;
        end = text.indexOf(delim, 0);

        try {
            if (start < end) {
                final Context ctx = getApplicationContext();
                String targetString = text.substring(start, end);
                SpannableStringBuilder ssb = new SpannableStringBuilder(targetString);
                ssb.setSpan(new NonUnderlinedClickableSpan(targetString) {
                    @Override
                    public void onClick(View v) {
                        Intent myIntent = new Intent(ctx, ActorDetails.class);
                        myIntent.putExtra("ActorName", tag);
                        myIntent.putExtra("seriesId", seriesId);
                        myIntent.putExtra("seriesName", seriesInfo.getName());
                        startActivityForResult(myIntent, 0);
                    }
                }, start, end, 0);
                ssb.setSpan(new TextAppearanceSpan(this, R.style.episode_link), 0, ssb.length(), 0); // Set the style of the text
                //ssb.setSpan(new AbsoluteSizeSpan((int)textSize, true), 0, ssb.length(), 0);            // Override the text size with the user's preference
                builtTags.append(ssb);
                if (text.substring(end + 1).indexOf(delim) >= 0)
                    builtTags.append(", ");
                text = text.substring(end + 1);
            }
        } catch (IndexOutOfBoundsException e) {
        }
    } while (start < end);

    return builtTags;
}

From source file:com.heath_bar.tvdb.SeriesOverview.java

/** Update the GUI with the specified rating */
private void setUserRatingTextView(int rating) {

    try {/*from w  w w.j  ava  2  s. c o  m*/
        TextView ratingTextView = (TextView) findViewById(R.id.rating);
        String communityRating = (seriesInfo == null) ? "?" : seriesInfo.getRating();
        String communityRatingText = communityRating + " / 10";

        String ratingTextA = communityRatingText + "  (";
        String ratingTextB = (rating == 0) ? "rate" : String.valueOf(rating);
        String ratingTextC = ")";

        int start = ratingTextA.length();
        int end = ratingTextA.length() + ratingTextB.length();

        SpannableStringBuilder ssb = new SpannableStringBuilder(ratingTextA + ratingTextB + ratingTextC);

        ssb.setSpan(new NonUnderlinedClickableSpan() {
            @Override
            public void onClick(View v) {
                showRatingDialog();
            }
        }, start, end, 0);

        ssb.setSpan(new TextAppearanceSpan(getApplicationContext(), R.style.episode_link), start, end, 0); // Set the style of the text
        ratingTextView.setText(ssb, BufferType.SPANNABLE);
        ratingTextView.setMovementMethod(LinkMovementMethod.getInstance());
    } catch (Exception e) {
        Log.e("SeriesOverview", "Failed to setUserRatingTextView: " + e.getMessage());
    }
}

From source file:com.gh4a.fragment.PullRequestFragment.java

private void fillLabels(List<Label> labels) {
    View labelGroup = mListHeaderView.findViewById(R.id.label_container);
    if (labels != null && !labels.isEmpty()) {
        TextView labelView = (TextView) mListHeaderView.findViewById(R.id.labels);
        SpannableStringBuilder builder = new SpannableStringBuilder();

        for (Label label : labels) {
            int pos = builder.length();
            IssueLabelSpan span = new IssueLabelSpan(getActivity(), label, true);
            builder.append(label.getName());
            builder.setSpan(span, pos, pos + label.getName().length(), 0);
        }//  w w w  . java  2  s  .com
        labelView.setText(builder);
        labelGroup.setVisibility(View.VISIBLE);
    } else {
        labelGroup.setVisibility(View.GONE);
    }
}

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

public Emoji.XImageSpan createAndPutChipForUser(TLRPC.User user) {
    LayoutInflater lf = (LayoutInflater) parentActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    View textView = lf.inflate(R.layout.group_create_bubble, null);
    TextView text = (TextView) textView.findViewById(R.id.bubble_text_view);
    text.setText(Utilities.formatName(user.first_name, user.last_name));

    int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    textView.measure(spec, spec);/*from  w  w  w  .ja v a2s.c  o m*/
    textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
    Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(b);
    canvas.translate(-textView.getScrollX(), -textView.getScrollY());
    textView.draw(canvas);
    textView.setDrawingCacheEnabled(true);
    Bitmap cacheBmp = textView.getDrawingCache();
    Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
    textView.destroyDrawingCache();

    final BitmapDrawable bmpDrawable = new BitmapDrawable(b);
    bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight());

    SpannableStringBuilder ssb = new SpannableStringBuilder("");
    Emoji.XImageSpan span = new Emoji.XImageSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE);
    allSpans.add(span);
    selectedContacts.put(user.id, span);
    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());
    return span;
}

From source file:android_network.hetnet.vpn_service.AdapterRule.java

private void markPro(MenuItem menu, String sku) {
    if (true) {/*from   w ww . j ava 2  s .c om*/
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        boolean dark = prefs.getBoolean("dark_theme", false);
        SpannableStringBuilder ssb = new SpannableStringBuilder("  " + menu.getTitle());
        ssb.setSpan(
                new ImageSpan(context,
                        dark ? R.drawable.ic_shopping_cart_white_24dp : R.drawable.ic_shopping_cart_black_24dp),
                0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        menu.setTitle(ssb);
    }
}

From source file:io.plaidapp.ui.HomeActivity.java

private void setNoFiltersEmptyTextVisibility(int visibility) {
    if (visibility == View.VISIBLE) {
        if (noFiltersEmptyText == null) {
            // create the no filters empty text
            ViewStub stub = (ViewStub) findViewById(R.id.stub_no_filters);
            noFiltersEmptyText = (TextView) stub.inflate();
            String emptyText = getString(R.string.no_filters_selected);
            int filterPlaceholderStart = emptyText.indexOf('\u08B4');
            int altMethodStart = filterPlaceholderStart + 3;
            SpannableStringBuilder ssb = new SpannableStringBuilder(emptyText);
            // show an image of the filter icon
            ssb.setSpan(new ImageSpan(this, R.drawable.ic_filter_small, ImageSpan.ALIGN_BASELINE),
                    filterPlaceholderStart, filterPlaceholderStart + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            // make the alt method (swipe from right) less prominent and italic
            ssb.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.text_secondary_light)),
                    altMethodStart, emptyText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new StyleSpan(Typeface.ITALIC), altMethodStart, emptyText.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            noFiltersEmptyText.setText(ssb);
            noFiltersEmptyText.setOnClickListener(new View.OnClickListener() {
                @Override/*from  ww w  .  j a  v  a 2  s.c o  m*/
                public void onClick(View v) {
                    drawer.openDrawer(GravityCompat.END);
                }
            });
        }
        noFiltersEmptyText.setVisibility(visibility);
    } else if (noFiltersEmptyText != null) {
        noFiltersEmptyText.setVisibility(visibility);
    }

}

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);
        }/*www  .j  a va2s  .c  o  m*/
        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.deliciousdroid.fragment.ViewBookmarkFragment.java

public void loadBookmark() {
    if (bookmark != null) {

        if (isMyself() && bookmark.getId() != 0) {
            try {
                int id = bookmark.getId();
                bookmark = BookmarkManager.GetById(id, base);
            } catch (ContentNotFoundException e) {
            }/*from ww  w .  j av a2s. c om*/
        }

        if (viewType == BookmarkViewType.VIEW) {
            mBookmarkView.setVisibility(View.VISIBLE);
            readSection.setVisibility(View.GONE);
            mWebContent.setVisibility(View.GONE);
            if (isMyself()) {
                Date d = new Date(bookmark.getTime());

                mTitle.setText(bookmark.getDescription());
                mUrl.setText(bookmark.getUrl());
                mNotes.setText(bookmark.getNotes());
                mTime.setText(d.toString());
                mUsername.setText(bookmark.getAccount());

                if (mIcon != null) {
                    if (!bookmark.getShared()) {
                        mIcon.setImageResource(R.drawable.padlock);
                    }
                }

                SpannableStringBuilder tagBuilder = new SpannableStringBuilder();

                for (Tag t : bookmark.getTags()) {
                    addTag(tagBuilder, t, tagOnClickListener);
                }

                mTags.setText(tagBuilder);
                mTags.setMovementMethod(LinkMovementMethod.getInstance());
            } else {

                Date d = new Date(bookmark.getTime());

                if (bookmark.getDescription() != null && !bookmark.getDescription().equals("null"))
                    mTitle.setText(bookmark.getDescription());

                mUrl.setText(bookmark.getUrl());

                if (bookmark.getNotes() != null && !bookmark.getNotes().equals("null"))
                    mNotes.setText(bookmark.getNotes());

                mTime.setText(d.toString());

                SpannableStringBuilder tagBuilder = new SpannableStringBuilder();

                for (Tag t : bookmark.getTags()) {
                    addTag(tagBuilder, t, userTagOnClickListener);
                }

                mTags.setText(tagBuilder);
                mTags.setMovementMethod(LinkMovementMethod.getInstance());

                if (bookmark.getAccount() != null) {
                    SpannableStringBuilder builder = new SpannableStringBuilder();
                    int start = builder.length();
                    builder.append(bookmark.getAccount());
                    int end = builder.length();

                    AccountSpan span = new AccountSpan(bookmark.getAccount());
                    span.setOnAccountClickListener(accountOnClickListener);

                    builder.setSpan(span, start, end, 0);

                    mUsername.setText(builder);
                }

                mUsername.setMovementMethod(LinkMovementMethod.getInstance());
            }
        } else if (viewType == BookmarkViewType.READ) {
            new GetArticleTask().execute(bookmark.getUrl());
        } else if (viewType == BookmarkViewType.WEB) {
            showInWebView();
        }
    }
}

From source file:io.realm.realmtasks.list.ItemViewHolder.java

public void setStrikeThroughRatio(float strikeThroughRatio) {
    final CharSequence text = this.text.getText();
    final int textLength = text.length();
    int firstLength = (int) (textLength * strikeThroughRatio);
    if (firstLength > textLength) {
        firstLength = textLength;//from  w w  w .j  a v  a2s  . c o  m
    } else if (firstLength == textLength - 1) {
        firstLength = textLength;
    }
    if (firstLength == previousFirstLength) {
        return;
    }
    previousFirstLength = firstLength;
    final int appendedLength = textLength - firstLength;
    final SpannableStringBuilder stringBuilder = new SpannableStringBuilder(text, 0, textLength);
    stringBuilder.clearSpans();
    this.text.setPaintFlags(this.text.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
    final CharacterStyle firstCharStyle, secondCharStyle;
    if (completed) {
        firstCharStyle = new ForegroundColorSpan(cellCompletedColor);
        secondCharStyle = new StrikethroughSpan();
    } else {
        firstCharStyle = new StrikethroughSpan();
        secondCharStyle = new ForegroundColorSpan(cellDefaultColor);
    }
    stringBuilder.setSpan(firstCharStyle, 0, firstLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    stringBuilder.setSpan(secondCharStyle, textLength - appendedLength, textLength,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    this.text.setText(stringBuilder);
}