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:org.mozilla.gecko.home.HistoryPanel.java

/**
 * Make Span that is clickable, italicized, and underlined
 * between the string markers <code>FORMAT_S1</code> and
 * <code>FORMAT_S2</code>./*  ww  w  . j a v  a 2s.c o m*/
 *
 * @param text String to format
 * @return formatted SpannableStringBuilder, or null if there
 * is not any text to format.
 */
private SpannableStringBuilder formatHintText(String text) {
    // Set formatting as marked by string placeholders.
    final int underlineStart = text.indexOf(FORMAT_S1);
    final int underlineEnd = text.indexOf(FORMAT_S2);

    // Check that there is text to be formatted.
    if (underlineStart >= underlineEnd) {
        return null;
    }

    final SpannableStringBuilder ssb = new SpannableStringBuilder(text);

    // Set italicization.
    ssb.setSpan(new StyleSpan(Typeface.ITALIC), 0, ssb.length(), 0);

    // Set clickable text.
    final ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View widget) {
            Telemetry.sendUIEvent(TelemetryContract.Event.ACTION, TelemetryContract.Method.HOMESCREEN,
                    "hint-private-browsing");
            try {
                final JSONObject json = new JSONObject();
                json.put("type", "Menu:Open");
                EventDispatcher.getInstance().dispatchEvent(json, null);
            } catch (JSONException e) {
                Log.e(LOGTAG, "Error forming JSON for Private Browsing contextual hint", e);
            }
        }
    };

    ssb.setSpan(clickableSpan, 0, text.length(), 0);

    // Remove underlining set by ClickableSpan.
    final UnderlineSpan noUnderlineSpan = new UnderlineSpan() {
        @Override
        public void updateDrawState(TextPaint textPaint) {
            textPaint.setUnderlineText(false);
        }
    };

    ssb.setSpan(noUnderlineSpan, 0, text.length(), 0);

    // Add underlining for "Private Browsing".
    ssb.setSpan(new UnderlineSpan(), underlineStart, underlineEnd, 0);

    ssb.delete(underlineEnd, underlineEnd + FORMAT_S2.length());
    ssb.delete(underlineStart, underlineStart + FORMAT_S1.length());

    return ssb;
}

From source file:com.viewpagerindicator.TabTextPageIndicator.java

/**
 * textview//from   www .  jav  a 2 s .  co 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.battlelancer.seriesguide.ui.dialogs.AddShowDialogFragment.java

private void populateShowViews(Show show) {
    if (show == null) {
        mButtonPositive.setEnabled(false);
        if (!AndroidUtils.isNetworkConnected(getActivity())) {
            overview.setText(R.string.offline);
        }/*from w w w  .  j ava 2  s  .c om*/
        return;
    }

    mButtonPositive.setEnabled(true);
    ButterKnife.apply(labelViews, VISIBLE, true);

    // title, overview
    title.setText(show.title);
    overview.setText(show.overview);

    SpannableStringBuilder meta = new SpannableStringBuilder();

    // status
    boolean isContinuing = JsonExportTask.ShowStatusExport.CONTINUING.equals(show.status);
    meta.append(getString(isContinuing ? R.string.show_isalive : R.string.show_isnotalive));
    // if continuing, paint status green
    meta.setSpan(
            new TextAppearanceSpan(getActivity(),
                    isContinuing ? R.style.TextAppearance_Subhead_Green : R.style.TextAppearance_Subhead_Dim),
            0, meta.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    meta.append("\n");

    // release day and time
    String[] values = TimeTools.formatToShowReleaseTimeAndDay(getActivity(), show.airtime, show.country,
            show.airday);
    meta.append(values[1]).append(" ").append(values[0]);
    meta.append("\n");

    // network, runtime
    meta.append(show.network);
    meta.append("\n");
    meta.append(getString(R.string.runtime_minutes, show.runtime));

    showmeta.setText(meta);

    // TheTVDB rating
    tvdbRating.setText(show.rating > 0 ? String.valueOf(show.rating) : getString(R.string.norating));

    // genres
    Utils.setValueOrPlaceholder(genres, Utils.splitAndKitTVDBStrings(show.genres));

    // original release
    Utils.setValueOrPlaceholder(released,
            TimeTools.getShowReleaseYear(show.firstAired, show.airtime, show.country));

    // poster
    Utils.loadPosterThumbnail(getActivity(), poster, show.poster);
}

From source file:cn.figo.mydemo.ui.activity.VideoActivity.java

private SpannableStringBuilder createSpannable(Drawable drawable) {
    String text = "bitmap";
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
    ImageSpan span = new ImageSpan(drawable);//ImageSpan.ALIGN_BOTTOM);
    spannableStringBuilder.setSpan(span, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    spannableStringBuilder.append("");
    spannableStringBuilder.setSpan(new BackgroundColorSpan(Color.parseColor("#8A2233B1")), 0,
            spannableStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    return spannableStringBuilder;
}

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

/** Populate the GUI with the data we've found */
public void PopulateStuff(TvEpisode theEpisode) {

    // Set Title//from www  .j av  a2 s  . co m
    TextView textview = (TextView) findViewById(R.id.title);
    textview.setVisibility(View.VISIBLE);
    textview.setText(theEpisode.getSeason() + "x" + String.format("%02d", theEpisode.getNumber()) + " "
            + theEpisode.getName());

    // Set Thumb
    if (theEpisode.getImage() != null
            && (theEpisode.getImage().getBitmap() == null || theEpisode.getImage().getUrl().equals(""))) {
        // do nothin
    } else {
        imageId = theEpisode.getImage().getId();
        ImageButton banner = (ImageButton) findViewById(R.id.episode_thumb);
        banner.setImageBitmap(theEpisode.getImage().getBitmap());
        banner.setVisibility(View.VISIBLE);
        banner.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                shareImage();
            }
        });
    }

    // Overview
    textview = (TextView) findViewById(R.id.overview_header);
    textview.setVisibility(View.VISIBLE);
    textview = (TextView) findViewById(R.id.overview);
    textview.setVisibility(View.VISIBLE);
    textview.setText(theEpisode.getOverview());

    // Director
    textview = (TextView) findViewById(R.id.director_header);
    textview.setVisibility(View.VISIBLE);
    textview = (TextView) findViewById(R.id.director);
    textview.setVisibility(View.VISIBLE);
    textview.setText(theEpisode.getDirector());

    // Writer
    textview = (TextView) findViewById(R.id.writer_header);
    textview.setVisibility(View.VISIBLE);
    textview = (TextView) findViewById(R.id.writer);
    textview.setVisibility(View.VISIBLE);
    textview.setText(theEpisode.getWriter());

    // Rating
    textview = (TextView) findViewById(R.id.rating_header);
    textview.setVisibility(View.VISIBLE);
    textview = (TextView) findViewById(R.id.rating);
    textview.setVisibility(View.VISIBLE);
    textview.setText(theEpisode.getRating() + " / 10");

    // First Aired
    textview = (TextView) findViewById(R.id.first_aired_header);
    textview.setVisibility(View.VISIBLE);
    textview = (TextView) findViewById(R.id.first_aired);
    textview.setVisibility(View.VISIBLE);
    textview.setText(DateUtil.toString(theEpisode.getAirDate()));

    // Guest Stars
    textview = (TextView) findViewById(R.id.guest_stars_header);
    textview.setVisibility(View.VISIBLE);
    textview = (TextView) findViewById(R.id.guest_stars);
    textview.setVisibility(View.VISIBLE);
    textview.setText(theEpisode.getGuestStars());

    textview = (TextView) findViewById(R.id.imdb_link);
    textview.setVisibility(View.VISIBLE);

    final String imdbId = theEpisode.getIMDB();
    if (imdbId != "") {
        SpannableStringBuilder ssb = new SpannableStringBuilder(getResources().getString(R.string.imdb));
        ssb.setSpan(new NonUnderlinedClickableSpan(getResources().getString(R.string.imdb)) {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://www.imdb.com/title/" + imdbId));
                startActivity(myIntent);
            }
        }, 0, ssb.length(), 0);

        ssb.setSpan(new TextAppearanceSpan(this, R.style.episode_link), 0, ssb.length(), 0); // Set the style of the text
        textview.setText(ssb, BufferType.SPANNABLE);
        textview.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

From source file:com.supermario.kanjilookandlearn.view.ScreenSlidePageFragment.java

private void initView() {
    initId();//from  w w w  .j av  a2s. c  om

    rootLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onCardClick(v);
        }
    });
    imageView.setImageDrawable(Utils.getDrawableFromAssets(getActivity(), kanjiItem.image));
    kanjiFaceTextView.setText(kanjiItem.kanji);

    // a SpannableStringBuilder containing text to display
    SpannableStringBuilder sb = new SpannableStringBuilder(kanjiItem.remember);

    // create a bold StyleSpan to be used on the SpannableStringBuilder
    StyleSpan b = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold

    int index = kanjiItem.remember.indexOf(kanjiItem.meanVietnamese);
    if (index >= 0) {
        // set only the name part of the SpannableStringBuilder to be bold --> 16, 16 + name.length()
        sb.setSpan(b, index, index + kanjiItem.meanVietnamese.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }

    kunyomiTextView.setText(kanjiItem.kunyomi);
    onyomiTextView.setText(kanjiItem.onyomi);

    rememberTextView.setText(sb);

    //        try {
    //            strokeWebView.loadDataWithBaseURL(null,Utils.getStringFromInputStream(Utils.getInputStreamFromAssets(getActivity(), "04e00")), "text/html", "UTF-8", null);
    //        } catch (IOException e) {
    //            e.printStackTrace();
    //        }

    if (kanjiItem.favorite == 1) {
        favoriteImageView.setImageResource(R.drawable.icon_favorite_active);
    } else {
        favoriteImageView.setImageResource(R.drawable.icon_favorite_inactive);
    }

    favoriteImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (kanjiItem.favorite == 0) {
                kanjiItem.favorite = 1;
                favoriteImageView.setImageResource(R.drawable.icon_favorite_active);
            } else {
                kanjiItem.favorite = 0;
                favoriteImageView.setImageResource(R.drawable.icon_favorite_inactive);
            }
            KanjiProvider.updateFavorite(getActivity(), kanjiItem);
        }
    });
}

From source file:com.tct.mail.browse.SubjectAndFolderView.java

public void setFolders(ConversationViewHeaderCallbacks callbacks, Account account, Conversation conv) {
    mVisibleFolders = true;/*from  ww w.j  a  v  a2 s  .  c o m*/
    final BidiFormatter bidiFormatter = getBidiFormatter();
    if (TextUtils.isEmpty(mSubject)) {
        mSubject = conv.subject;
    }
    final SpannableStringBuilder sb = new SpannableStringBuilder(bidiFormatter.unicodeWrap(mSubject));
    sb.append('\u0020');
    final Settings settings = account.settings;
    final int start = sb.length();
    if (settings.importanceMarkersEnabled && conv.isImportant()) {
        sb.append(".\u0020");
        sb.setSpan(new DynamicDrawableSpan(DynamicDrawableSpan.ALIGN_BASELINE) {
            @Override
            public Drawable getDrawable() {
                Drawable d = getContext().getResources()
                        .getDrawable(R.drawable.ic_email_caret_none_important_unread);
                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                return d;
            }
        }, start, start + 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    //TS: yanhua.chen 2015-12-22 EMAIL BUGFIX_1178365 MOD_S
    //        mFolderDisplayer.loadConversationFolders(conv, null /* ignoreFolder */, -1 /* ignoreFolderType */);
    //        mFolderDisplayer.appendFolderSpans(sb, bidiFormatter);

    //        final int end = sb.length();
    //        sb.setSpan(new ChangeLabelsSpan(callbacks), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    setText(sb);
    //TS: yanhua.chen 2015-11-4 EMAIL BUGFIX_851207 MOD_S
    //        if(isNeedMove()){
    //            setMovementMethod(LinkMovementMethod.getInstance());
    //        }
    //TS: yanhua.chen 2015-11-4 EMAIL BUGFIX_851207 MOD_E
    //TS: yanhua.chen 2015-12-22 EMAIL BUGFIX_1178365 MOD_E
}

From source file:app.abhijit.iter.MainActivity.java

private void setupGettingStartedHint() {
    TextView gettingStartedHint = (TextView) findViewById(R.id.hint_getting_started);
    int lineHeight = gettingStartedHint.getLineHeight();
    Drawable hamburgerIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_hamburger, null);
    hamburgerIcon.setBounds(0, 0, lineHeight, lineHeight);
    SpannableStringBuilder hintText = new SpannableStringBuilder();
    hintText.append(getResources().getString(R.string.hint_getting_started_1)).append(" ");
    hintText.setSpan(new ImageSpan(hamburgerIcon), hintText.length() - 1, hintText.length(), 0);
    hintText.append(getResources().getString(R.string.hint_getting_started_2));
    gettingStartedHint.setText(hintText);
}

From source file:org.mariotaku.twidere.view.NameView.java

public void updateText(@Nullable BidiFormatter formatter) {
    final SpannableStringBuilder sb = new SpannableStringBuilder();
    final String primaryText = mNameFirst ? mName : mScreenName;
    final String secondaryText = mNameFirst ? mScreenName : mName;
    if (primaryText != null) {
        int start = sb.length();
        if (formatter != null && !isInEditMode()) {
            sb.append(formatter.unicodeWrap(primaryText));
        } else {/*  w w  w.  ja  v a 2  s .c o m*/
            sb.append(primaryText);
        }
        int end = sb.length();
        sb.setSpan(mPrimaryTextColor, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        sb.setSpan(mPrimaryTextStyle, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        sb.setSpan(mPrimaryTextSize, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    sb.append(mTwoLine ? '\n' : ' ');
    if (secondaryText != null) {
        int start = sb.length();
        if (formatter != null && !isInEditMode()) {
            sb.append(formatter.unicodeWrap(secondaryText));
        } else {
            sb.append(secondaryText);
        }
        int end = sb.length();
        sb.setSpan(mSecondaryTextColor, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        sb.setSpan(mSecondaryTextStyle, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        sb.setSpan(mSecondaryTextSize, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    setText(sb);
}

From source file:nya.miku.wishmaster.ui.settings.AutohideActivity.java

@SuppressLint("InflateParams")
@Override//  w ww . jav  a 2 s  . co  m
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Object item = l.getItemAtPosition(position);
    final int changeId;
    if (item instanceof AutohideRule) {
        changeId = position - 1;
    } else {
        changeId = -1; //-1 - ?  
    }

    Context dialogContext = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
            ? new ContextThemeWrapper(this, R.style.Neutron_Medium)
            : this;
    View dialogView = LayoutInflater.from(dialogContext).inflate(R.layout.dialog_autohide_rule, null);
    final EditText regexEditText = (EditText) dialogView.findViewById(R.id.dialog_autohide_regex);
    final Spinner chanSpinner = (Spinner) dialogView.findViewById(R.id.dialog_autohide_chan_spinner);
    final EditText boardEditText = (EditText) dialogView.findViewById(R.id.dialog_autohide_boardname);
    final EditText threadEditText = (EditText) dialogView.findViewById(R.id.dialog_autohide_threadnum);
    final CheckBox inCommentCheckBox = (CheckBox) dialogView.findViewById(R.id.dialog_autohide_in_comment);
    final CheckBox inSubjectCheckBox = (CheckBox) dialogView.findViewById(R.id.dialog_autohide_in_subject);
    final CheckBox inNameCheckBox = (CheckBox) dialogView.findViewById(R.id.dialog_autohide_in_name);

    chanSpinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, chans));
    if (changeId != -1) {
        AutohideRule rule = (AutohideRule) item;
        regexEditText.setText(rule.regex);
        int chanPosition = chans.indexOf(rule.chanName);
        chanSpinner.setSelection(chanPosition != -1 ? chanPosition : 0);
        boardEditText.setText(rule.boardName);
        threadEditText.setText(rule.threadNumber);
        inCommentCheckBox.setChecked(rule.inComment);
        inSubjectCheckBox.setChecked(rule.inSubject);
        inNameCheckBox.setChecked(rule.inName);
    } else {
        chanSpinner.setSelection(0);
    }

    DialogInterface.OnClickListener save = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String regex = regexEditText.getText().toString();
            if (regex.length() == 0) {
                Toast.makeText(AutohideActivity.this, R.string.autohide_error_empty_regex, Toast.LENGTH_LONG)
                        .show();
                return;
            }

            try {
                Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL);
            } catch (Exception e) {
                CharSequence message = null;
                if (e instanceof PatternSyntaxException) {
                    String eMessage = e.getMessage();
                    if (!TextUtils.isEmpty(eMessage)) {
                        SpannableStringBuilder a = new SpannableStringBuilder(
                                getString(R.string.autohide_error_incorrect_regex));
                        a.append('\n');
                        int startlen = a.length();
                        a.append(eMessage);
                        a.setSpan(new TypefaceSpan("monospace"), startlen, a.length(),
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        message = a;
                    }
                }
                if (message == null)
                    message = getString(R.string.error_unknown);
                Toast.makeText(AutohideActivity.this, message, Toast.LENGTH_LONG).show();
                return;
            }

            AutohideRule rule = new AutohideRule();
            int spinnerSelectedPosition = chanSpinner.getSelectedItemPosition();
            rule.regex = regex;
            rule.chanName = spinnerSelectedPosition > 0 ? chans.get(spinnerSelectedPosition) : ""; // 0 ? = ? 
            rule.boardName = boardEditText.getText().toString();
            rule.threadNumber = threadEditText.getText().toString();
            rule.inComment = inCommentCheckBox.isChecked();
            rule.inSubject = inSubjectCheckBox.isChecked();
            rule.inName = inNameCheckBox.isChecked();

            if (!rule.inComment && !rule.inSubject && !rule.inName) {
                Toast.makeText(AutohideActivity.this, R.string.autohide_error_no_condition, Toast.LENGTH_LONG)
                        .show();
                return;
            }

            if (changeId == -1) {
                rulesJson.put(rule.toJson());
            } else {
                rulesJson.put(changeId, rule.toJson());
            }
            rulesChanged();
        }
    };
    AlertDialog dialog = new AlertDialog.Builder(this).setView(dialogView)
            .setTitle(changeId == -1 ? R.string.autohide_add_rule_title : R.string.autohide_edit_rule_title)
            .setPositiveButton(R.string.autohide_save_button, save)
            .setNegativeButton(android.R.string.cancel, null).create();
    dialog.setCanceledOnTouchOutside(false);
    dialog.show();
}