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() 

Source Link

Document

Create a new SpannableStringBuilder with empty contents

Usage

From source file:com.newcell.calltext.ui.messages.MessageFragment.java

/**
 * Format the string to show the Contact Name if they're a contact,
 * or just the phone number/*w w  w. j a va  2s  .  c o m*/
 * @param remoteContact The full SIP URI of the contact
 * @return The formatted string
 */
private CharSequence formatFrom(String remoteContact) {
    SpannableStringBuilder buf = new SpannableStringBuilder();

    CallerInfo callerInfo = CallerInfo.getCallerInfoFromSipUri(getActivity(), remoteContact);
    if (callerInfo != null && callerInfo.contactExists) {
        buf.append(callerInfo.name);
    } else {
        buf.append(SipUri.getDisplayedSimpleContact(remoteContact));
    }

    return buf;
}

From source file:com.android.mms.quickmessage.QuickMessage.java

private CharSequence formatMessage(String message) {
    SpannableStringBuilder buf = new SpannableStringBuilder();

    // Get the emojis preference
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    boolean enableEmojis = prefs.getBoolean(MessagingPreferenceActivity.ENABLE_EMOJIS, false);

    if (!TextUtils.isEmpty(message)) {
        SmileyParser parser = SmileyParser.getInstance();
        CharSequence smileyBody = parser.addSmileySpans(message);
        if (enableEmojis) {
            EmojiParser emojiParser = EmojiParser.getInstance();
            smileyBody = emojiParser.addEmojiSpans(smileyBody);
        }// w ww  .  j  a v a  2s.c  om
        buf.append(smileyBody);
    }
    return buf;
}

From source file:de.ub0r.android.lib.DonationHelper.java

/**
 * Show "donate" dialog.//w ww .ja  va  2 s . c o m
 * 
 * @param context
 *            {@link Context}
 * @param title
 *            title
 * @param btnDonate
 *            button text for donate
 * @param btnNoads
 *            button text for "i did a donation"
 * @param messages
 *            messages for dialog body
 */
public static void showDonationDialog(final Activity context, final String title, final String btnDonate,
        final String btnNoads, final String[] messages) {
    final Intent marketIntent = Market.getInstallAppIntent(context, DONATOR_PACKAGE, null);

    String btnTitle = String.format(btnDonate, "Play Store");

    SpannableStringBuilder sb = new SpannableStringBuilder();
    for (String m : messages) {
        sb.append(m);
        sb.append("\n");
    }
    sb.delete(sb.length() - 1, sb.length());
    sb.setSpan(new RelativeSizeSpan(0.75f), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    AlertDialog.Builder b = new AlertDialog.Builder(context);
    b.setTitle(title);
    b.setMessage(sb);
    b.setCancelable(true);
    b.setPositiveButton(btnTitle, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            try {
                context.startActivity(marketIntent);
            } catch (ActivityNotFoundException e) {
                Log.e(TAG, "activity not found", e);
                Toast.makeText(context, "activity not found", Toast.LENGTH_LONG).show();
            }
        }
    });
    b.setNeutralButton(btnNoads, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            try {
                context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                        "http://code.google.com/p/ub0rapps/downloads/list?" + "can=3&q=Product%3DDonator")));
            } catch (ActivityNotFoundException e) {
                Log.e(TAG, "activity not found", e);
                Toast.makeText(context, "activity not found", Toast.LENGTH_LONG).show();
            }
        }
    });
    b.show();
}

From source file:com.battlelancer.seriesguide.ui.EpisodeDetailsFragment.java

private void populateEpisodeData(Cursor cursor) {
    if (cursor == null || !cursor.moveToFirst()) {
        // no data to display
        if (mEpisodeContainer != null) {
            mEpisodeContainer.setVisibility(View.GONE);
        }//from w w w  . j  a v a 2  s .  c o m
        return;
    }

    mShowTvdbId = cursor.getInt(DetailsQuery.REF_SHOW_ID);
    mSeasonNumber = cursor.getInt(DetailsQuery.SEASON);
    mEpisodeNumber = cursor.getInt(DetailsQuery.NUMBER);
    mShowRunTime = cursor.getInt(DetailsQuery.SHOW_RUNTIME);
    mEpisodeReleaseTime = cursor.getLong(DetailsQuery.FIRST_RELEASE_MS);

    // title and description
    mEpisodeTitle = cursor.getString(DetailsQuery.TITLE);
    mTitle.setText(mEpisodeTitle);
    mDescription.setText(cursor.getString(DetailsQuery.OVERVIEW));

    // show title
    mShowTitle = cursor.getString(DetailsQuery.SHOW_TITLE);

    // release time and day
    SpannableStringBuilder timeAndNumbersText = new SpannableStringBuilder();
    if (mEpisodeReleaseTime != -1) {
        Date actualRelease = TimeTools.getEpisodeReleaseTime(getActivity(), mEpisodeReleaseTime);
        mReleaseDay.setText(TimeTools.formatToDate(getActivity(), actualRelease));
        // "in 15 mins (Fri)"
        timeAndNumbersText.append(getString(R.string.release_date_and_day,
                TimeTools.formatToRelativeLocalReleaseTime(getActivity(), actualRelease),
                TimeTools.formatToLocalReleaseDay(actualRelease)).toUpperCase(Locale.getDefault()));
        timeAndNumbersText.append("  ");
    } else {
        mReleaseDay.setText(R.string.unknown);
    }
    // absolute number (e.g. relevant for Anime): "ABSOLUTE 142"
    int numberStartIndex = timeAndNumbersText.length();
    int absoluteNumber = cursor.getInt(DetailsQuery.ABSOLUTE_NUMBER);
    if (absoluteNumber > 0) {
        timeAndNumbersText.append(getString(R.string.episode_number_absolute)).append(" ")
                .append(String.valueOf(absoluteNumber));
        // de-emphasize number
        timeAndNumbersText.setSpan(new TextAppearanceSpan(getActivity(), R.style.TextAppearance_Caption_Dim),
                numberStartIndex, timeAndNumbersText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    mReleaseTime.setText(timeAndNumbersText);

    // guest stars
    Utils.setLabelValueOrHide(mLabelGuestStars, mGuestStars,
            Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.GUESTSTARS)));
    // DVD episode number
    Utils.setLabelValueOrHide(mLabelDvd, mDvd, cursor.getDouble(DetailsQuery.DVDNUMBER));
    // directors
    Utils.setValueOrPlaceholder(mDirectors,
            Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.DIRECTORS)));
    // writers
    Utils.setValueOrPlaceholder(mWriters, Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.WRITERS)));

    // last TVDb edit date
    long lastEditSeconds = cursor.getLong(DetailsQuery.LASTEDIT);
    if (lastEditSeconds > 0) {
        mLastEdit.setText(DateUtils.formatDateTime(getActivity(), lastEditSeconds * 1000,
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME));
    } else {
        mLastEdit.setText(R.string.unknown);
    }

    // ratings
    mRatingsContainer.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            rateOnTrakt();
        }
    });
    mRatingsContainer.setFocusable(true);
    CheatSheet.setup(mRatingsContainer, R.string.action_rate);
    // TVDb rating
    String tvdbRating = cursor.getString(DetailsQuery.RATING);
    if (!TextUtils.isEmpty(tvdbRating)) {
        mTvdbRating.setText(tvdbRating);
    }
    // trakt ratings
    loadTraktRatings(true);

    // episode image
    final String imagePath = cursor.getString(DetailsQuery.IMAGE);
    mImageContainer.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent fullscreen = new Intent(getActivity(), FullscreenImageActivity.class);
            fullscreen.putExtra(FullscreenImageActivity.InitBundle.IMAGE_PATH, imagePath);
            ActivityCompat.startActivity(getActivity(), fullscreen, ActivityOptionsCompat
                    .makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight()).toBundle());
        }
    });
    loadImage(imagePath);

    // check in button
    final int episodeTvdbId = cursor.getInt(DetailsQuery._ID);
    mCheckinButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // display a check-in dialog
            CheckInDialogFragment f = CheckInDialogFragment.newInstance(getActivity(), episodeTvdbId);
            f.show(getFragmentManager(), "checkin-dialog");
            fireTrackerEvent("Check-In");
        }
    });
    CheatSheet.setup(mCheckinButton);

    // watched button
    mEpisodeFlag = cursor.getInt(DetailsQuery.WATCHED);
    boolean isWatched = EpisodeTools.isWatched(mEpisodeFlag);
    Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mWatchedButton, 0,
            isWatched ? Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableWatched)
                    : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableWatch),
            0, 0);
    mWatchedButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // disable button, will be re-enabled on data reload once action completes
            v.setEnabled(false);
            onToggleWatched();
            fireTrackerEvent("Toggle watched");
        }
    });
    mWatchedButton.setEnabled(true);
    mWatchedButton.setText(isWatched ? R.string.action_unwatched : R.string.action_watched);
    CheatSheet.setup(mWatchedButton, isWatched ? R.string.action_unwatched : R.string.action_watched);

    // collected button
    mCollected = cursor.getInt(DetailsQuery.COLLECTED) == 1;
    Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mCollectedButton, 0,
            mCollected ? R.drawable.ic_collected
                    : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableCollect),
            0, 0);
    mCollectedButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // disable button, will be re-enabled on data reload once action completes
            v.setEnabled(false);
            onToggleCollected();
            fireTrackerEvent("Toggle collected");
        }
    });
    mCollectedButton.setEnabled(true);
    mCollectedButton.setText(mCollected ? R.string.action_collection_remove : R.string.action_collection_add);
    CheatSheet.setup(mCollectedButton,
            mCollected ? R.string.action_collection_remove : R.string.action_collection_add);

    // skip button
    boolean isSkipped = EpisodeTools.isSkipped(mEpisodeFlag);
    if (isWatched) {
        // if watched do not allow skipping
        mSkipButton.setVisibility(View.INVISIBLE);
    } else {
        mSkipButton.setVisibility(View.VISIBLE);
        Utils.setCompoundDrawablesRelativeWithIntrinsicBounds(mSkipButton, 0,
                isSkipped ? R.drawable.ic_skipped
                        : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableSkip),
                0, 0);
        mSkipButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // disable button, will be re-enabled on data reload once action completes
                v.setEnabled(false);
                onToggleSkipped();
                fireTrackerEvent("Toggle skipped");
            }
        });
        mSkipButton.setText(isSkipped ? R.string.action_dont_skip : R.string.action_skip);
        CheatSheet.setup(mSkipButton, isSkipped ? R.string.action_dont_skip : R.string.action_skip);
    }
    mSkipButton.setEnabled(true);

    // service buttons
    ServiceUtils.setUpTraktButton(mShowTvdbId, mSeasonNumber, mEpisodeNumber, mTraktButton, TAG);
    // IMDb
    String imdbId = cursor.getString(DetailsQuery.IMDBID);
    if (TextUtils.isEmpty(imdbId)) {
        // fall back to show IMDb id
        imdbId = cursor.getString(DetailsQuery.SHOW_IMDBID);
    }
    ServiceUtils.setUpImdbButton(imdbId, mImdbButton, TAG, getActivity());
    // TVDb
    final int seasonTvdbId = cursor.getInt(DetailsQuery.REF_SEASON_ID);
    ServiceUtils.setUpTvdbButton(mShowTvdbId, seasonTvdbId, getEpisodeTvdbId(), mTvdbButton, TAG);
    // trakt comments
    mCommentsButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), TraktShoutsActivity.class);
            intent.putExtras(TraktShoutsActivity.createInitBundleEpisode(mShowTvdbId, mSeasonNumber,
                    mEpisodeNumber, mEpisodeTitle));
            ActivityCompat.startActivity(getActivity(), intent, ActivityOptionsCompat
                    .makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight()).toBundle());
            fireTrackerEvent("Comments");
        }
    });

    mEpisodeContainer.setVisibility(View.VISIBLE);
}

From source file:org.bobstuff.bobball.ActivityStateEnum.java

private void showWonScreen() {
    activityState = ActivityStateEnum.GAMEWON;

    Statistics.saveHighestLevel(numPlayers, gameManager.getLevel() + 1);
    levelSeries++;/*ww  w . j ava  2 s.  co  m*/
    Statistics.saveLongestSeries(levelSeries);

    GameState gs = gameManager.getCurrGameState();
    Grid currGrid = gs.getGrid();

    SpannableStringBuilder percentageCleared = new SpannableStringBuilder();

    String percentageString = currGrid.getPercentCompleteFloat(1) + "%";

    String totalPercentageString = getString(R.string.percentageCleared, percentageString);

    int player1Color = gs.getPlayer(1).getColor();

    SpannableString percentage = new SpannableString(totalPercentageString);
    int percentageStart = totalPercentageString.length() - percentageString.length();
    int percentageEnd = totalPercentageString.length();

    percentage.setSpan(new ForegroundColorSpan(player1Color), percentageStart, percentageEnd,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    percentageCleared.append(percentage);

    messageView.setText(getString(R.string.levelCompleted, gameManager.getLevel()));
    button.setText(R.string.nextLevel);
    retryButton.setVisibility(View.GONE);
    button.setVisibility(View.VISIBLE);
    backToLevelSelectButton.setVisibility(View.GONE);
    this.percentageCleared.setText(percentageCleared);
    this.percentageCleared.setVisibility(View.VISIBLE);

    if (numPlayers > 1) {
        totalPercentageCleared
                .setText(getString(R.string.totalPercentageCleared, currGrid.getPercentCompleteFloat() + "%"));
        totalPercentageCleared.setVisibility(View.VISIBLE);
    }

    bonusPoints.setText(getString(R.string.bonusPoints, gameManager.getBonusPoints(gs, gs.getPlayer(1))));
    bonusPoints.setVisibility(View.VISIBLE);

    setMessageViewsVisible(true);
}

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;//  w  ww .  j a  va2 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.googlecode.eyesfree.brailleback.BrailleIME.java

public void updateDisplay() {
    if (mExtractedText == null) {
        return;/*from  w  w  w.  j  a  v a2 s . c  om*/
    }
    DisplayManager displayManager = getCurrentDisplayManager();
    if (displayManager == null) {
        return;
    }
    EditorInfo ei = getCurrentInputEditorInfo();
    if (ei == null) {
        LogUtils.log(this, Log.WARN, "No input editor info");
        return;
    }
    CharSequence label = ei.label;
    CharSequence hint = ei.hintText;
    if (TextUtils.isEmpty(label)) {
        label = hint;
        hint = null;
    }
    SpannableStringBuilder text = new SpannableStringBuilder();
    if (!TextUtils.isEmpty(label)) {
        text.append(label);
        text.append(": "); // TODO: Put in a resource.
    }
    int editStart = text.length();
    text.append(mCurrentText);
    addMarkingSpan(text, EDIT_TEXT_SPAN, editStart);
    CharSequence actionLabel = getActionLabel();
    if (actionLabel != null) {
        text.append(" [");
        text.append(actionLabel);
        text.append("]");
        addMarkingSpan(text, ACTION_LABEL_SPAN, text.length() - (actionLabel.length() + 2));
    }
    DisplaySpans.addSelection(text, editStart + mSelectionStart, editStart + mSelectionEnd);
    displayManager.setContent(new DisplayManager.Content(text).setPanStrategy(DisplayManager.Content.PAN_CURSOR)
            .setSplitParagraphs(isMultiLineField()));
}

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);
        }/*from   w w w. jav  a  2s  .  c o  m*/
        labelView.setText(builder);
        labelGroup.setVisibility(View.VISIBLE);
    } else {
        labelGroup.setVisibility(View.GONE);
    }
}

From source file:org.catrobat.catroid.ui.MainMenuActivity.java

private void setMainMenuButtonContinueText() {
    Button mainMenuButtonContinue = (Button) this.findViewById(R.id.main_menu_button_continue);
    TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan(this, R.style.MainMenuButtonTextSecondLine);
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
    String mainMenuContinue = this.getString(R.string.main_menu_continue);

    spannableStringBuilder.append(mainMenuContinue);
    spannableStringBuilder.append("\n");
    spannableStringBuilder.append(Utils.getCurrentProjectName(this));

    spannableStringBuilder.setSpan(textAppearanceSpan, mainMenuContinue.length() + 1,
            spannableStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

    mainMenuButtonContinue.setText(spannableStringBuilder);
}

From source file:com.kyakujin.android.tagnotepad.ui.NoteListFragment.java

/**
 * About/*  w ww  . jav a  2  s . c o  m*/
 */
private void showAboutDialog() {
    PackageManager pm = getActivity().getPackageManager();
    String packageName = getActivity().getPackageName();
    String versionName;
    try {
        PackageInfo info = pm.getPackageInfo(packageName, 0);
        versionName = info.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        versionName = "N/A";
    }

    SpannableStringBuilder aboutBody = new SpannableStringBuilder();

    SpannableString mailAddress = new SpannableString(getString(R.string.mailto));
    mailAddress.setSpan(new ClickableSpan() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse(getString(R.string.description_mailto)));
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.description_mail_subject));
            startActivity(intent);
        }
    }, 0, mailAddress.length(), 0);

    aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));
    aboutBody.append("\n");
    aboutBody.append(mailAddress);

    LayoutInflater layoutInflater = (LayoutInflater) getActivity()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.fragment_about_dialog, null);
    aboutBodyView.setText(aboutBody);
    aboutBodyView.setMovementMethod(LinkMovementMethod.getInstance());

    AlertDialog dlg = new AlertDialog.Builder(getActivity()).setTitle(R.string.alert_title_about)
            .setView(aboutBodyView).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).create();
    dlg.show();
}