Example usage for android.text SpannableStringBuilder append

List of usage examples for android.text SpannableStringBuilder append

Introduction

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

Prototype

public SpannableStringBuilder append(char text) 

Source Link

Usage

From source file:org.kontalk.ui.view.TextContentView.java

@Override
public void bind(long databaseId, TextComponent component, Pattern highlight) {
    mComponent = component;// w w w .j  a v a2 s .c o m

    SpannableStringBuilder formattedMessage = formatMessage(highlight);
    setTextStyle(this);

    // linkify!
    if (formattedMessage.length() < MAX_AFFORDABLE_SIZE)
        Linkify.addLinks(formattedMessage, Linkify.ALL);

    /*
     * workaround for bugs:
     * http://code.google.com/p/android/issues/detail?id=17343
     * http://code.google.com/p/android/issues/detail?id=22493
     * applies from Honeycomb to JB 4.2.2 afaik
     */
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB
            && android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1)
        // from http://stackoverflow.com/a/12303155/1045199
        formattedMessage.append("\u200b"); // was: \u2060

    setText(formattedMessage);
}

From source file:com.juick.android.ThreadActivity.java

public void onReplySelected(final JuickMessage msg) {
    selectedReply = msg;//  w w w.  j  av a2  s  . c  o  m
    rid = msg.getRID();
    if (rid > 0) {
        SpannableStringBuilder ssb = new SpannableStringBuilder();
        String inreplyto = getResources().getString(R.string.In_reply_to_) + " ";
        ssb.append(inreplyto).append(msg.Text);
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, inreplyto.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvReplyTo.setText(ssb);
        setHeight(replyToContainer, ActionBar.LayoutParams.WRAP_CONTENT);
        showThread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tf.showThread(msg, false);
            }
        });
    } else {
        setHeight(replyToContainer, 0);
    }
}

From source file:com.taobao.weex.dom.WXTextDomObject.java

/**
 * Update layout according to {@link #mText} and span
 * @param width the specified width.//from   w  ww.ja va 2 s.c  om
 * @param forceWidth If true, force the text width to the specified width, otherwise, text width
 *                   may equals to or be smaller than the specified width.
 * @param previousLayout the result of previous layout, could be null.
 */
private @NonNull Layout createLayout(float width, boolean forceWidth, @Nullable Layout previousLayout) {
    float textWidth;
    textWidth = getTextWidth(mTextPaint, width, forceWidth);
    Layout layout;
    if (!FloatUtil.floatsEqual(previousWidth, textWidth) || previousLayout == null) {
        boolean forceRtl = false;
        Object direction = getStyles().get(Constants.Name.DIRECTION);
        if (direction != null && "text".equals(mType)) {
            forceRtl = direction.equals(Constants.Name.RTL);
        }
        layout = StaticLayoutProxy.create(spanned, mTextPaint, (int) Math.ceil(textWidth),
                Layout.Alignment.ALIGN_NORMAL, 1, 0, false, forceRtl);
    } else {
        layout = previousLayout;
    }
    if (mNumberOfLines != UNSET && mNumberOfLines > 0 && mNumberOfLines < layout.getLineCount()) {
        int lastLineStart, lastLineEnd;
        lastLineStart = layout.getLineStart(mNumberOfLines - 1);
        lastLineEnd = layout.getLineEnd(mNumberOfLines - 1);
        if (lastLineStart < lastLineEnd) {
            SpannableStringBuilder builder = null;
            if (lastLineStart > 0) {
                builder = new SpannableStringBuilder(spanned.subSequence(0, lastLineStart));
            } else {
                builder = new SpannableStringBuilder();
            }
            Editable lastLine = new SpannableStringBuilder(spanned.subSequence(lastLineStart, lastLineEnd));
            builder.append(truncate(lastLine, mTextPaint, (int) Math.ceil(textWidth), textOverflow));
            adjustSpansRange(spanned, builder);
            spanned = builder;
            return new StaticLayout(spanned, mTextPaint, (int) Math.ceil(textWidth),
                    Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
        }
    }
    return layout;
}

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 w  w  .j a  v a  2  s.  co  m*/
        builder.append(timeSpannable);
        displayedTime = builder;
    }
    return displayedTime;
}

From source file:com.android.mms.transaction.MessagingNotification.java

private static CharSequence formatSenders(Context context, ArrayList<NotificationInfo> senders) {
    final TextAppearanceSpan notificationSenderSpan = new TextAppearanceSpan(context,
            R.style.NotificationPrimaryText);

    String separator = context.getString(R.string.enumeration_comma); // ", "
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
    int len = senders.size();
    for (int i = 0; i < len; i++) {
        if (i > 0) {
            spannableStringBuilder.append(separator);
        }/*ww w . j  a  v a 2 s .com*/
        spannableStringBuilder.append(senders.get(i).mSender.getName());
    }
    spannableStringBuilder.setSpan(notificationSenderSpan, 0, spannableStringBuilder.length(), 0);
    return spannableStringBuilder;
}

From source file:at.jclehner.rxdroid.DoseView.java

private void updateView() {
    mStatus = STATUS_INDETERMINATE;//from   w  w w.  j av a 2  s  .co m
    mIntakeStatus.setImageDrawable(null);

    if (mDrug != null) {
        if (!mDrug.isActive())
            mDoseText.setText("0");
        else if (!mDisplayDose.isZero()) {
            setStatus(STATUS_TAKEN);

            SpannableStringBuilder sb = new SpannableStringBuilder(Util.prettify(mDisplayDose));

            final Date lastScheduleUpdate = mDrug.getLastScheduleUpdateDate();

            if (lastScheduleUpdate == null || !mDate.before(lastScheduleUpdate)) {
                final Fraction scheduledDose = mDrug.getDose(mDoseTime, mDate);
                int cmp = mDisplayDose.compareTo(scheduledDose);
                String suffix;

                if (cmp < 0)
                    suffix = "-";
                else if (cmp > 0)
                    suffix = "+";
                else
                    suffix = null;

                if (suffix != null) {
                    sb.append(suffix);
                    sb.setSpan(new SuperscriptSpan(), sb.length() - 1, sb.length(), 0);
                }
            }

            mDoseText.setText(sb);
        } else {
            Fraction dose = mDrug.getDose(mDoseTime, mDate);
            mDoseText.setText(Util.prettify(dose));

            if (mIntakeCount == 0) {
                if (!dose.isZero() && !mDrug.isAsNeeded()) {
                    int offset = (int) Settings.getTrueDoseTimeEndOffset(mDoseTime);
                    Date end = DateTime.add(mDate, Calendar.MILLISECOND, offset);

                    if (DateTime.now().after(end))
                        setStatus(STATUS_MISSED);
                }
            } else
                setStatus(STATUS_IGNORED);
        }

    } else if (mDisplayDose != null)
        mDoseText.setText(Util.prettify(mDisplayDose));

    if ("0".equals(mDoseText.getText())) {
        String zeroStr = null;

        if (BuildConfig.DEBUG)
            zeroStr = Settings.getString("doseview_zero");

        if (zeroStr == null)
            zeroStr = "-";

        mDoseText.setText(zeroStr);

    }
}

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

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

From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java

private CharSequence formatMessage(String contact, String body, String contentType) {
    System.out.println("MessageAdapter.java in formatMessage() ");
    SpannableStringBuilder buf = new SpannableStringBuilder();
    if (!TextUtils.isEmpty(body)) {
        // Converts html to spannable if ContentType is "text/html".
        if (contentType != null && "text/html".equals(contentType)) {
            buf.append("\n");
            buf.append(Html.fromHtml(body));
        } else {/*  w w w .  j  a  va 2 s . co  m*/
            SmileyParser parser = SmileyParser.getInstance();
            buf.append(parser.addSmileySpans(body));
        }
    }

    // We always show two lines because the optional icon bottoms are
    // aligned with the
    // bottom of the text field, assuming there are two lines for the
    // message and the sent time.
    buf.append("\n");
    int startOffset = buf.length();
    startOffset = buf.length();
    buf.setSpan(mTextSmallSpan, startOffset, buf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    System.out.println("formatMessage:" + buf);
    return buf;
}

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

/**
 * About//from   ww  w.  jav  a2  s . c  om
 */
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();
}

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   www  .  j  a v a2s  .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);
}