Example usage for android.text SpannableString SpannableString

List of usage examples for android.text SpannableString SpannableString

Introduction

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

Prototype

public SpannableString(CharSequence source) 

Source Link

Document

For the backward compatibility reasons, this constructor copies all spans including android.text.NoCopySpan .

Usage

From source file:com.android.tv.dvr.ui.DvrUiHelper.java

@NonNull
public static CharSequence getStyledTitleWithEpisodeNumber(Context context, String title, String seasonNumber,
        String episodeNumber, int episodeNumberStyleResId) {
    if (TextUtils.isEmpty(title)) {
        return "";
    }/* w w  w . j  av  a2 s.  co  m*/
    SpannableStringBuilder builder;
    if (TextUtils.isEmpty(seasonNumber) || seasonNumber.equals("0")) {
        builder = TextUtils.isEmpty(episodeNumber) ? new SpannableStringBuilder(title)
                : new SpannableStringBuilder(Html.fromHtml(context.getString(
                        R.string.program_title_with_episode_number_no_season, title, episodeNumber)));
    } else {
        builder = new SpannableStringBuilder(Html.fromHtml(context
                .getString(R.string.program_title_with_episode_number, title, seasonNumber, episodeNumber)));
    }
    Object[] spans = builder.getSpans(0, builder.length(), Object.class);
    if (spans.length > 0) {
        if (episodeNumberStyleResId != 0) {
            builder.setSpan(new TextAppearanceSpan(context, episodeNumberStyleResId),
                    builder.getSpanStart(spans[0]), builder.getSpanEnd(spans[0]),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        builder.removeSpan(spans[0]);
    }
    return new SpannableString(builder);
}

From source file:info.guardianproject.otr.app.im.app.MessageView.java

private CharSequence formatPresenceUpdates(String contact, int type, boolean isGroupChat, boolean scrolling) {
    String body;// w  w w .j  av  a 2 s.c  om

    Resources resources = getResources();

    switch (type) {
    case Imps.MessageType.PRESENCE_AVAILABLE:
        body = resources.getString(isGroupChat ? R.string.contact_joined : R.string.contact_online, contact);
        break;

    case Imps.MessageType.PRESENCE_AWAY:
        body = resources.getString(R.string.contact_away, contact);
        break;

    case Imps.MessageType.PRESENCE_DND:
        body = resources.getString(R.string.contact_busy, contact);
        break;

    case Imps.MessageType.PRESENCE_UNAVAILABLE:
        body = resources.getString(isGroupChat ? R.string.contact_left : R.string.contact_offline, contact);
        break;

    default:
        return null;
    }

    if (scrolling) {
        return body;
    } else {
        SpannableString spanText = new SpannableString(body);
        int len = spanText.length();
        spanText.setSpan(new StyleSpan(Typeface.ITALIC), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanText.setSpan(new RelativeSizeSpan((float) 0.8), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanText;
    }
}

From source file:com.forrestguice.suntimeswidget.SuntimesUtils.java

public static SpannableString createBoldColorSpan(String text, String toBold, int color, int pointSizePixels) {
    SpannableString span = new SpannableString(text);
    int start = text.indexOf(toBold);
    int end = start + toBold.length();
    span.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), start, end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    span.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    span.setSpan(new AbsoluteSizeSpan(pointSizePixels), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return span;// www  . jav a 2 s .  co m
}

From source file:com.gm.goldencity.util.Utils.java

/**
 * Apply typeface to a plane text and return spannableString
 *
 * @param text     Text that you want to apply typeface
 * @param typeface Typeface that you want to apply to your text
 * @return spannableString// www . j  a v  a  2s.  c om
 */
public static SpannableString applyTypefaceToString(String text, final Typeface typeface) {
    SpannableString spannableString = new SpannableString(text);
    spannableString.setSpan(new MetricAffectingSpan() {
        @Override
        public void updateMeasureState(TextPaint p) {
            p.setTypeface(typeface);

            // Note: This flag is required for proper typeface rendering
            p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }

        @Override
        public void updateDrawState(TextPaint tp) {
            tp.setTypeface(typeface);

            // Note: This flag is required for proper typeface rendering
            tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }
    }, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spannableString;
}

From source file:org.awesomeapp.messenger.ui.MessageListItem.java

private SpannableString formatTimeStamp(Date date, int messageType, MessageListItem.DeliveryState delivery,
        EncryptionState encryptionState, String nickname) {

    StringBuilder deliveryText = new StringBuilder();

    if (nickname != null) {
        deliveryText.append(nickname);//from w w  w .  j a v  a  2  s. co m
        deliveryText.append(' ');
    }

    deliveryText.append(sPrettyTime.format(date));

    SpannableString spanText = null;

    spanText = new SpannableString(deliveryText.toString());

    if (delivery != null) {
        deliveryText.append(' ');
        //this is for delivery

        if (messageType == Imps.MessageType.POSTPONED) {
            //do nothing
            deliveryText.append("X");
            spanText = new SpannableString(deliveryText.toString());
            int len = spanText.length();
            spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_message_wait_grey), len - 1, len,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else if (delivery == DeliveryState.DELIVERED) {

            if (encryptionState == EncryptionState.ENCRYPTED
                    || encryptionState == EncryptionState.ENCRYPTED_AND_VERIFIED) {
                deliveryText.append("XX");
                spanText = new SpannableString(deliveryText.toString());
                int len = spanText.length();

                spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_delivered_grey), len - 2, len - 1,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_encrypted_grey), len - 1, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            } else {
                deliveryText.append("X");
                spanText = new SpannableString(deliveryText.toString());
                int len = spanText.length();
                spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_delivered_grey), len - 1, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            }

        } else if (delivery == DeliveryState.UNDELIVERED) {

            if (encryptionState == EncryptionState.ENCRYPTED
                    || encryptionState == EncryptionState.ENCRYPTED_AND_VERIFIED) {
                deliveryText.append("XX");
                spanText = new SpannableString(deliveryText.toString());
                int len = spanText.length();
                spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_sent_grey), len - 2, len - 1,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_encrypted_grey), len - 1, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                deliveryText.append("XX");
                spanText = new SpannableString(deliveryText.toString());
                int len = spanText.length();
                spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_sent_grey), len - 1, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            }

        } else if (delivery == DeliveryState.NEUTRAL) {

            if (encryptionState == EncryptionState.ENCRYPTED
                    || encryptionState == EncryptionState.ENCRYPTED_AND_VERIFIED) {
                deliveryText.append("XX");
                spanText = new SpannableString(deliveryText.toString());
                int len = spanText.length();
                spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_sent_grey), len - 2, len - 1,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_encrypted_grey), len - 1, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                deliveryText.append("X");
                spanText = new SpannableString(deliveryText.toString());
                int len = spanText.length();
                spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_sent_grey), len - 1, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            }

        }

    } else {
        if (encryptionState == EncryptionState.ENCRYPTED
                || encryptionState == EncryptionState.ENCRYPTED_AND_VERIFIED) {
            deliveryText.append('X');
            spanText = new SpannableString(deliveryText.toString());
            int len = spanText.length();

            if (encryptionState == EncryptionState.ENCRYPTED
                    || encryptionState == EncryptionState.ENCRYPTED_AND_VERIFIED)
                spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_encrypted_grey), len - 1, len,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else if (messageType == Imps.MessageType.OUTGOING) {
            //do nothing
            deliveryText.append("X");
            spanText = new SpannableString(deliveryText.toString());
            int len = spanText.length();
            spanText.setSpan(new ImageSpan(getContext(), R.drawable.ic_message_wait_grey), len - 1, len,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    return spanText;
}

From source file:com.geecko.QuickLyric.fragment.LyricsViewFragment.java

@SuppressLint("SetTextI18n")
public void update(Lyrics lyrics, View layout, boolean animation) {
    File musicFile = null;//from w  ww.ja va  2  s. c om
    Bitmap cover = null;
    if (PermissionsChecker.hasPermission(getActivity(), "android.permission.READ_EXTERNAL_STORAGE")) {
        musicFile = Id3Reader.getFile(getActivity(), lyrics.getOriginalArtist(), lyrics.getOriginalTrack());
        cover = Id3Reader.getCover(getActivity(), lyrics.getArtist(), lyrics.getTitle());
    }
    setCoverArt(cover, null);
    boolean artCellDownload = Integer.valueOf(
            PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("pref_artworks", "0")) == 0;
    if (cover == null)
        new CoverArtLoader().execute(lyrics, this.getActivity(),
                artCellDownload || OnlineAccessVerifier.isConnectedWifi(getActivity()));
    getActivity().findViewById(R.id.edit_tags_btn).setEnabled(true);
    getActivity().findViewById(R.id.edit_tags_btn)
            .setVisibility(musicFile == null || !musicFile.canWrite() || lyrics.isLRC()
                    || Id3Reader.getLyrics(getActivity(), lyrics.getArtist(), lyrics.getTitle()) == null
                            ? View.GONE
                            : View.VISIBLE);
    TextSwitcher textSwitcher = ((TextSwitcher) layout.findViewById(R.id.switcher));
    LrcView lrcView = (LrcView) layout.findViewById(R.id.lrc_view);
    View v = getActivity().findViewById(R.id.tracks_msg);
    if (v != null)
        ((ViewGroup) v.getParent()).removeView(v);
    TextView artistTV = (TextView) getActivity().findViewById(R.id.artist);
    TextView songTV = (TextView) getActivity().findViewById(R.id.song);
    final TextView id3TV = (TextView) layout.findViewById(R.id.source_tv);
    TextView writerTV = (TextView) layout.findViewById(R.id.writer_tv);
    TextView copyrightTV = (TextView) layout.findViewById(R.id.copyright_tv);
    RelativeLayout bugLayout = (RelativeLayout) layout.findViewById(R.id.error_msg);
    this.mLyrics = lyrics;
    if (SDK_INT >= ICE_CREAM_SANDWICH)
        beamLyrics(lyrics, this.getActivity());
    new PresenceChecker().execute(this, new String[] { lyrics.getArtist(), lyrics.getTitle(),
            lyrics.getOriginalArtist(), lyrics.getOriginalTrack() });

    if (lyrics.getArtist() != null)
        artistTV.setText(lyrics.getArtist());
    else
        artistTV.setText("");
    if (lyrics.getTitle() != null)
        songTV.setText(lyrics.getTitle());
    else
        songTV.setText("");
    if (lyrics.getCopyright() != null) {
        copyrightTV.setText("Copyright: " + lyrics.getCopyright());
        copyrightTV.setVisibility(View.VISIBLE);
    } else {
        copyrightTV.setText("");
        copyrightTV.setVisibility(View.GONE);
    }
    if (lyrics.getWriter() != null) {
        if (lyrics.getWriter().contains(","))
            writerTV.setText("Writers:\n" + lyrics.getWriter());
        else
            writerTV.setText("Writer:" + lyrics.getWriter());
        writerTV.setVisibility(View.VISIBLE);
    } else {
        writerTV.setText("");
        writerTV.setVisibility(View.GONE);
    }
    if (isActiveFragment)
        ((RefreshIcon) getActivity().findViewById(R.id.refresh_fab)).show();
    EditText newLyrics = (EditText) getActivity().findViewById(R.id.edit_lyrics);
    if (newLyrics != null)
        newLyrics.setText("");

    if (lyrics.getFlag() == Lyrics.POSITIVE_RESULT) {
        if (!lyrics.isLRC()) {
            textSwitcher.setVisibility(View.VISIBLE);
            lrcView.setVisibility(View.GONE);
            if (animation)
                textSwitcher.setText(Html.fromHtml(lyrics.getText()));
            else
                textSwitcher.setCurrentText(Html.fromHtml(lyrics.getText()));
        } else {
            textSwitcher.setVisibility(View.GONE);
            lrcView.setVisibility(View.VISIBLE);
            lrcView.setOriginalLyrics(lyrics);
            lrcView.setSourceLrc(lyrics.getText());
            if (isActiveFragment)
                ((ControllableAppBarLayout) getActivity().findViewById(R.id.appbar)).expandToolbar(true);
            updateLRC();
        }

        bugLayout.setVisibility(View.INVISIBLE);
        id3TV.setMovementMethod(LinkMovementMethod.getInstance());
        if ("Storage".equals(lyrics.getSource())) {
            id3TV.setVisibility(View.VISIBLE);
            SpannableString text = new SpannableString(getString(R.string.from_id3));
            text.setSpan(new UnderlineSpan(), 1, text.length() - 1, 0);
            id3TV.setText(text);
            id3TV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((MainActivity) getActivity()).id3PopUp(id3TV);
                }
            });
        } else {
            id3TV.setOnClickListener(null);
            id3TV.setVisibility(View.GONE);
        }
        mScrollView.post(new Runnable() {
            @Override
            public void run() {
                mScrollView.scrollTo(0, 0); //only useful when coming from localLyricsFragment
                mScrollView.smoothScrollTo(0, 0);
            }
        });
    } else {
        textSwitcher.setText("");
        textSwitcher.setVisibility(View.INVISIBLE);
        lrcView.setVisibility(View.INVISIBLE);
        bugLayout.setVisibility(View.VISIBLE);
        int message;
        int whyVisibility;
        if (lyrics.getFlag() == Lyrics.ERROR || !OnlineAccessVerifier.check(getActivity())) {
            message = R.string.connection_error;
            whyVisibility = TextView.GONE;
        } else {
            message = R.string.no_results;
            whyVisibility = TextView.VISIBLE;
            updateSearchView(false, lyrics.getTitle(), false);
        }
        TextView whyTextView = ((TextView) bugLayout.findViewById(R.id.bugtext_why));
        ((TextView) bugLayout.findViewById(R.id.bugtext)).setText(message);
        whyTextView.setVisibility(whyVisibility);
        whyTextView.setPaintFlags(whyTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        id3TV.setVisibility(View.GONE);
    }
    stopRefreshAnimation();
    getActivity().getIntent().setAction("");
    getActivity().invalidateOptionsMenu();
}

From source file:com.msopentech.applicationgateway.EnterpriseBrowserActivity.java

public void showSettingsPopup(View v) {
    try {//  ww  w  .j  a  va2 s  .  c o  m
        PopupMenu popup = new PopupMenu(this, v);
        MenuInflater inflater = popup.getMenuInflater();
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                case R.id.menu_connection: {
                    showAgentsList();
                    return true;
                }
                case R.id.menu_sign_in_or_out: {
                    if (mIsSigninRequired) {
                        // Menu item in sign in mode.
                        //TODO: 
                        showSignIn(null, true);
                        return true;
                    }

                    // Clean up the session.
                    mTraits.sessionID = null;
                    mTraits.token = null;
                    mTraits.agent = null;

                    // Indicate the condition.
                    mIsSigninRequired = true;

                    //Remove all tabs except one.
                    mCustomTabHost.resetTabs();

                    mUrlEditTextView.setText("");

                    mProgressBarView.setProgress(0);

                    // Disable the reload button and set the right image for it.
                    mReloadButtonView.setEnabled(false);
                    mReloadButtonView.setImageResource(R.drawable.reload_button);

                    mStatusButtonView.setImageResource(R.drawable.connection_red);

                    // Since it's the user's intention to sign out, his
                    // history must be dropped.
                    PersistenceManager.dropContent(PersistenceManager.ContentType.HISTORY);

                    return true;
                }
                // Removed from RELEASE version. Should be active for development ONLY.                       
                //                        case R.id.menu_advanced_router_settings: {
                //                            showAdvancedRouterSettings(null);
                //                        }
                default: {
                    return false;
                }
                }
            }
        });
        inflater.inflate(R.menu.settings_menu, popup.getMenu());

        if (mIsSigninRequired) {
            MenuItem signItem = popup.getMenu().findItem(R.id.menu_sign_in_or_out);
            signItem.setTitle(getResources().getString(R.string.browser_menu_item_sign_in));
        }

        // Assumes that agent always has a display name. If display name is not present agent is considered to be not connected.
        MenuItem agentItem = popup.getMenu().findItem(R.id.menu_connection);
        String status = getResources().getString(R.string.browser_menu_item_choose_connection_not_connected);
        if (mTraits != null && mTraits.agent != null && !TextUtils.isEmpty(mTraits.agent.getDisplayName())) {
            status = mTraits.agent.getDisplayName();
        }
        Spannable span = new SpannableString(
                getResources().getString(R.string.browser_menu_item_choose_connection, status));
        span.setSpan(new RelativeSizeSpan(0.8f), 18, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(Color.GRAY), 18, span.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        agentItem.setTitle(span);

        popup.show();
    } catch (final Exception e) {
        Utility.showAlertDialog(EnterpriseBrowserActivity.class.getSimpleName()
                + ".showSettingsPopup(): Failed. " + e.toString(), EnterpriseBrowserActivity.this);
    }
}

From source file:github.daneren2005.dsub.util.Util.java

private static void showDialog(Context context, int icon, String title, String message) {
    SpannableString ss = new SpannableString(message);
    Linkify.addLinks(ss, Linkify.ALL);/*ww  w .  ja v  a2s  . c o  m*/

    AlertDialog dialog = new AlertDialog.Builder(context).setIcon(icon).setTitle(title).setMessage(ss)
            .setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int i) {
                    dialog.dismiss();
                }
            }).show();

    ((TextView) dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:com.atwal.wakeup.battery.util.Utilities.java

public static SpannableString highlightKeywords(int color, String text, String keywords,
        boolean actionFirstMatch) {

    if (text != null && keywords != null && text.trim().length() == keywords.trim().length()) {
        return SpannableString.valueOf(text.trim());
    }/*from   ww  w.  j a v a 2  s  .  c om*/

    SpannableString s = new SpannableString(text);
    Pattern p = Pattern.compile(keywords, Pattern.LITERAL);
    Matcher m = p.matcher(s);
    while (m.find()) {
        int end = m.end();
        try {
            if (s.charAt(end) != ' ') {
                s.setSpan(new UnderlineSpan(), end, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                s.setSpan(new UnderlineSpan(), end + 1, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (actionFirstMatch) {
            break;
        }
    }
    return s;
}

From source file:tw.com.geminihsu.app01.fragment.Fragment_PickUpAirPlane.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    MenuItem item = menu.add(Menu.NONE, ACTIONBAR_MENU_ITEM_SUMMIT, Menu.NONE, getString(R.string.menu_take));
    SpannableString spanString = new SpannableString(item.getTitle().toString());
    spanString.setSpan(new ForegroundColorSpan(Color.WHITE), 0, spanString.length(), 0); //fix the color to white
    item.setTitle(spanString);/*from ww w. j a va  2s.com*/

    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    super.onCreateOptionsMenu(menu, inflater);
}