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:es.usc.citius.servando.calendula.activities.ScheduleCreationActivity.java

public void onMedicineSelected(Medicine m, boolean step) {

    ScheduleHelper.instance().setSelectedMed(m);

    if (!step) {//from w ww  . ja va  2s.c  o m
        autoStepDone = true;
    }

    if (!autoStepDone) {
        autoStepDone = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mViewPager.setCurrentItem(1);
            }
        }, 500);
    }

    if (mScheduleId == -1) {
        String titleStart = getString(R.string.title_create_schedule_activity);
        String medName = " (" + m.name() + ")";
        String fullTitle = titleStart + medName;

        SpannableString title = new SpannableString(fullTitle);
        title.setSpan(new RelativeSizeSpan(0.7f), titleStart.length(), titleStart.length() + medName.length(),
                0);
        title.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.white_50)), titleStart.length(),
                titleStart.length() + medName.length(), 0);
        getSupportActionBar().setTitle(title);
    }
}

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

/**
 * About/*from w  w  w  . jav a 2  s .co  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();
}

From source file:de.baumann.thema.FragmentSound.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.help:
        SpannableString s;/*  w w w.j  av  a 2 s.c o m*/

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            s = new SpannableString(Html.fromHtml(getString(R.string.help_sound), Html.FROM_HTML_MODE_LEGACY));
        } else {
            //noinspection deprecation
            s = new SpannableString(Html.fromHtml(getString(R.string.help_sound)));
        }
        Linkify.addLinks(s, Linkify.WEB_URLS);

        final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.sound)
                .setMessage(s).setPositiveButton(getString(R.string.yes), null);
        dialog.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.marshalchen.common.uimodule.modifysys.PagerTitleStrip.java

SpannableString changeSpanString(String temp, int position, int color) {

    try {//  w w w . j a v a  2s.  co m
        temp = temp.replaceAll("-", " - ");

        SpannableString ss = new SpannableString(temp);
        Matrix matrix = new Matrix();

        matrix.postRotate(180);

        Bitmap bitmaporg = BitmapFactory.decodeResource(getResources(), R.drawable.ico_arrow2x);
        if (color == 2) {
            bitmaporg = BitmapFactory.decodeResource(getResources(), R.drawable.ico_arrow_grey2x);
        }
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmaporg, 0, 0, bitmaporg.getWidth(), bitmaporg.getHeight(),
                matrix, true);
        BitmapDrawable bmd = new BitmapDrawable(getResources(), resizedBitmap);
        BitmapDrawable bm = new BitmapDrawable(getResources(), bitmaporg);
        Drawable drawable = position == 0 ? bm : bmd;
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 12 / 10,
                drawable.getIntrinsicHeight() * 12 / 10);
        ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);

        ss.setSpan(imageSpan, temp.indexOf("-"), temp.indexOf("-") + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        return ss;
    } catch (Exception e) {
        e.printStackTrace();
        Logs.e(e, "");
        return null;
    }
}

From source file:com.coinblesk.client.utils.UIUtils.java

public static SpannableString toFriendlyFeeString(Context context, Transaction tx) {
    Coin fee = tx.getFee();/* w  w w. j a  v  a  2  s  .  c om*/
    ExchangeRate exchangeRate = tx.getExchangeRate();
    if (fee == null) {
        return new SpannableString("");
    }

    StringBuffer friendlyFee = new StringBuffer(UIUtils.formatCoin(context, fee));
    int feeLength = friendlyFee.length();

    int exchangeRateLength = feeLength;
    if (exchangeRate != null) {
        friendlyFee.append(" ~ " + exchangeRate.coinToFiat(fee).toFriendlyString());
        exchangeRateLength = friendlyFee.length();
    }

    SpannableString friendlySpannable = new SpannableString(friendlyFee);
    friendlySpannable.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.main_color_400)),
            feeLength, exchangeRateLength, 0);
    return friendlySpannable;

}

From source file:com.keepassdroid.EntryActivity.java

private void showSamsungDialog() {
    String text = getString(R.string.clipboard_error).concat(System.getProperty("line.separator"))
            .concat(getString(R.string.clipboard_error_url));
    SpannableString s = new SpannableString(text);
    TextView tv = new TextView(this);
    tv.setText(s);/*  w  ww  . ja va2  s .  com*/
    tv.setAutoLinkMask(RESULT_OK);
    tv.setMovementMethod(LinkMovementMethod.getInstance());
    Linkify.addLinks(s, Linkify.WEB_URLS);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.clipboard_error_title)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).setView(tv).show();

}

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

private static void handlePriority(int maxChars, String messageInfoString, ConversationInfo conversationInfo,
        ArrayList<SpannableString> styledSenders, ArrayList<String> displayableSenderNames,
        ArrayList<String> displayableSenderEmails, String account, final TextAppearanceSpan unreadStyleSpan,
        final CharacterStyle readStyleSpan, final boolean showToHeader) {
    boolean shouldAddPhotos = displayableSenderEmails != null;
    int maxPriorityToInclude = -1; // inclusive
    int numCharsUsed = messageInfoString.length(); // draft, number drafts,
                                                   // count
    int numSendersUsed = 0;
    int numCharsToRemovePerWord = 0;
    int maxFoundPriority = 0;
    if (numCharsUsed > maxChars) {
        numCharsToRemovePerWord = numCharsUsed - maxChars;
    }//from  w  w  w . jav  a2s. co  m

    final Map<Integer, Integer> priorityToLength = PRIORITY_LENGTH_MAP_CACHE.get();
    try {
        priorityToLength.clear();
        int senderLength;
        for (ParticipantInfo info : conversationInfo.participantInfos) {
            final String senderName = info.name;
            senderLength = !TextUtils.isEmpty(senderName) ? senderName.length() : 0;
            priorityToLength.put(info.priority, senderLength);
            maxFoundPriority = Math.max(maxFoundPriority, info.priority);
        }
        while (maxPriorityToInclude < maxFoundPriority) {
            if (priorityToLength.containsKey(maxPriorityToInclude + 1)) {
                int length = numCharsUsed + priorityToLength.get(maxPriorityToInclude + 1);
                if (numCharsUsed > 0)
                    length += 2;
                // We must show at least two senders if they exist. If we don't
                // have space for both
                // then we will truncate names.
                if (length > maxChars && numSendersUsed >= 2) {
                    break;
                }
                numCharsUsed = length;
                numSendersUsed++;
            }
            maxPriorityToInclude++;
        }
    } finally {
        PRIORITY_LENGTH_MAP_CACHE.release(priorityToLength);
    }
    // We want to include this entry if
    // 1) The onlyShowUnread flags is not set
    // 2) The above flag is set, and the message is unread
    ParticipantInfo currentParticipant;
    SpannableString spannableDisplay;
    CharacterStyle style;
    boolean appendedElided = false;
    Map<String, Integer> displayHash = Maps.newHashMap();
    String firstDisplayableSenderEmail = null;
    String firstDisplayableSender = null;
    for (int i = 0; i < conversationInfo.participantInfos.size(); i++) {
        currentParticipant = conversationInfo.participantInfos.get(i);
        final String currentEmail = currentParticipant.email;

        final String currentName = currentParticipant.name;
        String nameString = !TextUtils.isEmpty(currentName) ? currentName : "";
        if (nameString.length() == 0) {
            // if we're showing the To: header, show the object version of me.
            nameString = getMe(showToHeader /* useObjectMe */);
        }
        if (numCharsToRemovePerWord != 0) {
            nameString = nameString.substring(0, Math.max(nameString.length() - numCharsToRemovePerWord, 0));
        }

        final int priority = currentParticipant.priority;
        style = CharacterStyle.wrap(currentParticipant.readConversation ? readStyleSpan : unreadStyleSpan);
        if (priority <= maxPriorityToInclude) {
            spannableDisplay = new SpannableString(sBidiFormatter.unicodeWrap(nameString));
            // Don't duplicate senders; leave the first instance, unless the
            // current instance is also unread.
            int oldPos = displayHash.containsKey(currentName) ? displayHash.get(currentName) : DOES_NOT_EXIST;
            // If this sender doesn't exist OR the current message is
            // unread, add the sender.
            if (oldPos == DOES_NOT_EXIST || !currentParticipant.readConversation) {
                // If the sender entry already existed, and is right next to the
                // current sender, remove the old entry.
                if (oldPos != DOES_NOT_EXIST && i > 0 && oldPos == i - 1 && oldPos < styledSenders.size()) {
                    // Remove the old one!
                    styledSenders.set(oldPos, null);
                    if (shouldAddPhotos && !TextUtils.isEmpty(currentEmail)) {
                        displayableSenderEmails.remove(currentEmail);
                        displayableSenderNames.remove(currentName);
                    }
                }
                displayHash.put(currentName, i);
                spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0);
                styledSenders.add(spannableDisplay);
            }
        } else {
            if (!appendedElided) {
                spannableDisplay = new SpannableString(sElidedString);
                spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0);
                appendedElided = true;
                styledSenders.add(spannableDisplay);
            }
        }
        if (shouldAddPhotos) {
            String senderEmail = TextUtils.isEmpty(currentName) ? account
                    : TextUtils.isEmpty(currentEmail) ? currentName : currentEmail;
            if (i == 0) {
                // Always add the first sender!
                firstDisplayableSenderEmail = senderEmail;
                firstDisplayableSender = currentName;
            } else {
                if (!Objects.equal(firstDisplayableSenderEmail, senderEmail)) {
                    int indexOf = displayableSenderEmails.indexOf(senderEmail);
                    if (indexOf > -1) {
                        displayableSenderEmails.remove(indexOf);
                        displayableSenderNames.remove(indexOf);
                    }
                    displayableSenderEmails.add(senderEmail);
                    displayableSenderNames.add(currentName);
                    if (displayableSenderEmails.size() > DividedImageCanvas.MAX_DIVISIONS) {
                        displayableSenderEmails.remove(0);
                        displayableSenderNames.remove(0);
                    }
                }
            }
        }
    }
    if (shouldAddPhotos && !TextUtils.isEmpty(firstDisplayableSenderEmail)) {
        if (displayableSenderEmails.size() < DividedImageCanvas.MAX_DIVISIONS) {
            displayableSenderEmails.add(0, firstDisplayableSenderEmail);
            displayableSenderNames.add(0, firstDisplayableSender);
        } else {
            displayableSenderEmails.set(0, firstDisplayableSenderEmail);
            displayableSenderNames.set(0, firstDisplayableSender);
        }
    }
}

From source file:com.tandong.sa.sherlock.widget.SuggestionsAdapter.java

private CharSequence formatUrl(CharSequence url) {
    if (mUrlColor == null) {
        // Lazily get the URL color from the current theme.
        TypedValue colorValue = new TypedValue();
        mContext.getTheme().resolveAttribute(
                mContext.getResources().getIdentifier("textColorSearchUrl", "attr", mContext.getPackageName()),
                // mContext.getTheme().resolveAttribute(R.attr.textColorSearchUrl,
                colorValue, true);/*  ww  w .ja va2  s  .c o m*/
        mUrlColor = mContext.getResources().getColorStateList(colorValue.resourceId);
    }

    SpannableString text = new SpannableString(url);
    text.setSpan(new TextAppearanceSpan(null, 0, 0, mUrlColor, null), 0, url.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return text;
}

From source file:in.animeshpathak.nextbus.NextBusMain.java

/**
 * Creates the Application Info dialog with clickable links.
 * /*from w w  w .j  a va 2  s  . c  o  m*/
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
private void showVersionInfoDialog() throws UnsupportedEncodingException, IOException {
    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle(getString(R.string.app_name) + " " + getString(R.string.version_name));

    AssetManager assetManager = getResources().getAssets();
    String versionInfoFile = getString(R.string.versioninfo_asset);
    InputStreamReader reader = new InputStreamReader(assetManager.open(versionInfoFile), "UTF-8");
    BufferedReader br = new BufferedReader(reader);
    StringBuffer sbuf = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
        sbuf.append(line);
        sbuf.append("\r\n");
    }

    final ScrollView scroll = new ScrollView(this);
    final TextView message = new TextView(this);
    final SpannableString sWlinks = new SpannableString(sbuf.toString());
    Linkify.addLinks(sWlinks, Linkify.WEB_URLS);
    message.setText(sWlinks);
    message.setMovementMethod(LinkMovementMethod.getInstance());
    message.setPadding(15, 15, 15, 15);
    scroll.addView(message);
    alertDialog.setView(scroll);
    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // nothing to do, just dismiss dialog
        }
    });
    alertDialog.show();
}

From source file:com.andrewshu.android.reddit.threads.ThreadsListActivity.java

public static void fillThreadsListItemView(int position, View view, ThingInfo item, ListActivity activity,
        HttpClient client, RedditSettings settings,
        ThumbnailOnClickListenerFactory thumbnailOnClickListenerFactory) {

    Resources res = activity.getResources();

    TextView titleView = (TextView) view.findViewById(R.id.title);
    TextView votesView = (TextView) view.findViewById(R.id.votes);
    TextView numCommentsSubredditView = (TextView) view.findViewById(R.id.numCommentsSubreddit);
    TextView nsfwView = (TextView) view.findViewById(R.id.nsfw);
    //        TextView submissionTimeView = (TextView) view.findViewById(R.id.submissionTime);
    ImageView voteUpView = (ImageView) view.findViewById(R.id.vote_up_image);
    ImageView voteDownView = (ImageView) view.findViewById(R.id.vote_down_image);
    View thumbnailContainer = view.findViewById(R.id.thumbnail_view);
    FrameLayout thumbnailFrame = (FrameLayout) view.findViewById(R.id.thumbnail_frame);
    ImageView thumbnailImageView = (ImageView) view.findViewById(R.id.thumbnail);
    ProgressBar indeterminateProgressBar = (ProgressBar) view.findViewById(R.id.indeterminate_progress);

    // Set the title and domain using a SpannableStringBuilder
    SpannableStringBuilder builder = new SpannableStringBuilder();
    String title = item.getTitle();
    if (title == null)
        title = "";
    SpannableString titleSS = new SpannableString(title);
    int titleLen = title.length();
    titleSS.setSpan(//from  ww w. java2  s  . c  o m
            new TextAppearanceSpan(activity,
                    Util.getTextAppearanceResource(settings.getTheme(), android.R.style.TextAppearance_Large)),
            0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    String domain = item.getDomain();
    if (domain == null)
        domain = "";
    int domainLen = domain.length();
    SpannableString domainSS = new SpannableString("(" + item.getDomain() + ")");
    domainSS.setSpan(
            new TextAppearanceSpan(activity,
                    Util.getTextAppearanceResource(settings.getTheme(), android.R.style.TextAppearance_Small)),
            0, domainLen + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (Util.isLightTheme(settings.getTheme())) {
        if (item.isClicked()) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.purple));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.blue));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        domainSS.setSpan(new ForegroundColorSpan(res.getColor(R.color.gray_50)), 0, domainLen + 2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        if (item.isClicked()) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.gray_50));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        domainSS.setSpan(new ForegroundColorSpan(res.getColor(R.color.gray_75)), 0, domainLen + 2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    builder.append(titleSS).append(" ").append(domainSS);
    titleView.setText(builder);

    votesView.setText("" + item.getScore());
    numCommentsSubredditView.setText(Util.showNumComments(item.getNum_comments()) + "  " + item.getSubreddit());

    if (item.isOver_18()) {
        nsfwView.setVisibility(View.VISIBLE);
    } else {
        nsfwView.setVisibility(View.GONE);
    }

    // Set the up and down arrow colors based on whether user likes
    if (settings.isLoggedIn()) {
        if (item.getLikes() == null) {
            voteUpView.setImageResource(R.drawable.vote_up_gray);
            voteDownView.setImageResource(R.drawable.vote_down_gray);
            votesView.setTextColor(res.getColor(R.color.gray_75));
        } else if (item.getLikes() == true) {
            voteUpView.setImageResource(R.drawable.vote_up_red);
            voteDownView.setImageResource(R.drawable.vote_down_gray);
            votesView.setTextColor(res.getColor(R.color.arrow_red));
        } else {
            voteUpView.setImageResource(R.drawable.vote_up_gray);
            voteDownView.setImageResource(R.drawable.vote_down_blue);
            votesView.setTextColor(res.getColor(R.color.arrow_blue));
        }
    } else {
        voteUpView.setImageResource(R.drawable.vote_up_gray);
        voteDownView.setImageResource(R.drawable.vote_down_gray);
        votesView.setTextColor(res.getColor(R.color.gray_75));
    }

    // Thumbnails open links
    if (thumbnailContainer != null) {
        if (Common.shouldLoadThumbnails(activity, settings)) {
            thumbnailContainer.setVisibility(View.VISIBLE);

            if (item.getUrl() != null) {
                OnClickListener thumbnailOnClickListener = thumbnailOnClickListenerFactory
                        .getThumbnailOnClickListener(item, activity);
                if (thumbnailOnClickListener != null) {
                    thumbnailFrame.setOnClickListener(thumbnailOnClickListener);
                }
            }

            // Show thumbnail based on ThingInfo
            if ("default".equals(item.getThumbnail()) || "self".equals(item.getThumbnail())
                    || StringUtils.isEmpty(item.getThumbnail())) {
                indeterminateProgressBar.setVisibility(View.GONE);
                thumbnailImageView.setVisibility(View.VISIBLE);
                thumbnailImageView.setImageResource(R.drawable.go_arrow);
            } else {
                indeterminateProgressBar.setVisibility(View.GONE);
                thumbnailImageView.setVisibility(View.VISIBLE);
                if (item.getThumbnailBitmap() != null) {
                    thumbnailImageView.setImageBitmap(item.getThumbnailBitmap());
                } else {
                    thumbnailImageView.setImageBitmap(null);
                    new ShowThumbnailsTask(activity, client, R.drawable.go_arrow)
                            .execute(new ThumbnailLoadAction(item, thumbnailImageView, position));
                }
            }

            // Set thumbnail background based on current theme
            if (Util.isLightTheme(settings.getTheme()))
                thumbnailFrame.setBackgroundResource(R.drawable.thumbnail_background_light);
            else
                thumbnailFrame.setBackgroundResource(R.drawable.thumbnail_background_dark);
        } else {
            // if thumbnails disabled, hide thumbnail icon
            thumbnailContainer.setVisibility(View.GONE);
        }
    }
}