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.dwdesign.tweetings.activity.ComposeActivity.java

private String doShrink(String text) {
    ArrayList<Hyperlink> listOfLinks = new ArrayList<Hyperlink>();

    SpannableString linkableText = new SpannableString(text);
    Pattern hyperLinksPattern = Pattern
            .compile("([Hh][tT][tT][pP][sS]?:\\/\\/[^ ,'\">\\]\\)]*[^\\. ,'\">\\]\\)])");
    gatherLinks(listOfLinks, linkableText, hyperLinksPattern);

    for (int i = 0; i < listOfLinks.size(); i++) {
        Hyperlink link = listOfLinks.get(i);
        final String provider = mPreferences.getString(PREFERENCE_KEY_URL_SHORTENER, "tinyurl");

        if (!link.textSpan.toString().toLowerCase().contains("http://tl.gd")
                && !link.textSpan.toString().toLowerCase().contains("http://bit.ly")
                && !link.textSpan.toString().toLowerCase().contains("http://t.co")
                && !link.textSpan.toString().toLowerCase().contains("http://tinyurl.com")
                && !link.textSpan.toString().toLowerCase().contains("http://is.gd")
                && !link.textSpan.toString().toLowerCase().contains("http://tr.im")
                && !link.textSpan.toString().toLowerCase().contains("http://twitpic.com")
                && !link.textSpan.toString().toLowerCase().contains("http://yfrog.com")
                && !link.textSpan.toString().toLowerCase().contains("http://pic.gd")
                && !link.textSpan.toString().toLowerCase().contains("http://lockerz.com")
                && !link.textSpan.toString().toLowerCase().contains("http://twitgoo.com")
                && !link.textSpan.toString().toLowerCase().contains("http://twitrpix.com")
                && !link.textSpan.toString().toLowerCase().contains("http://img.ly")
                && !link.textSpan.toString().toLowerCase().contains("http://j.mp")
                && !link.textSpan.toString().toLowerCase().contains("http://cli.cs")) {
            try {
                String finalUrl = "";

                if (provider.equals("googl")) {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost postRequest = new HttpPost("https://www.googleapis.com/urlshortener/v1/url");
                    postRequest.addHeader("Content-Type", "application/json");

                    StringEntity reqEntity = new StringEntity(
                            "{\"longUrl\": \"" + link.textSpan.toString() + "\"}", HTTP.UTF_8);
                    postRequest.setEntity(reqEntity);

                    HttpResponse response = httpClient.execute(postRequest);

                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                    String sResponse;
                    StringBuilder s = new StringBuilder();

                    while ((sResponse = reader.readLine()) != null) {
                        s = s.append(sResponse);
                    }/*from   w  ww .  j  a  v  a  2s.co m*/

                    JSONObject jObject = new JSONObject(s.toString());

                    text = text.replace(link.textSpan.toString(), jObject.getString("id"));

                } else {
                    if (provider.equals("tinyurl")) {
                        finalUrl = "http://tinyurl.com/api-create.php?url="
                                + URLEncoder.encode(link.textSpan.toString());
                    } else if (provider.equals("isgd")) {
                        finalUrl = "http://is.gd/api.php?longurl="
                                + URLEncoder.encode(link.textSpan.toString());
                    } else if (provider.equals("bitly")) {
                        finalUrl = "http://api.bitly.com/v3/shorten?format=txt&login=" + BITLY_USER + "&apiKey="
                                + BITLY_API_KEY + "&longUrl=" + URLEncoder.encode(link.textSpan.toString());
                    } else if (provider.equals("jmp")) {
                        finalUrl = "http://api.bitly.com/v3/shorten?domain=j.mp&format=txt&login=" + BITLY_USER
                                + "&apiKey=" + BITLY_API_KEY + "&longUrl="
                                + URLEncoder.encode(link.textSpan.toString());
                    } else if (provider.equals("vgd")) {
                        finalUrl = "http://v.gd/create.php?format=simple&url="
                                + URLEncoder.encode(link.textSpan.toString());
                    } else if (provider.equals("trim")) {
                        finalUrl = "http://api.tr.im/v1/trim_simple?url="
                                + URLEncoder.encode(link.textSpan.toString());
                    } else if (provider.equals("googl")) {
                        finalUrl = "http://v.gd/create.php?format=simple&url="
                                + URLEncoder.encode(link.textSpan.toString());
                    }
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpResponse response = httpclient.execute(new HttpGet(finalUrl));

                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                    String sResponse;
                    StringBuilder s = new StringBuilder();

                    while ((sResponse = reader.readLine()) != null) {
                        s = s.append(sResponse);
                    }
                    text = text.replace(link.textSpan.toString(), s.toString());

                }

            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Network exception" + e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }

        }

    }

    return text;

}

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

private void createSubject(final boolean isUnread) {
    final String badgeText = mHeader.badgeText == null ? "" : mHeader.badgeText;
    String subject = filterTag(getContext(), mHeader.conversation.subject);
    subject = Conversation.getSubjectForDisplay(mContext, badgeText, subject);

    /// TCT: add for search term highlight
    // process subject and snippet respectively @{
    SpannableStringBuilder subjectToHighlight = new SpannableStringBuilder(subject);
    boolean hasFilter = (mSearchParams != null && !TextUtils.isEmpty(mSearchParams.mFilter));
    if (hasFilter) {
        boolean fieldMatchedSubject = (mSearchParams != null
                && (SearchParams.SEARCH_FIELD_SUBJECT.equals(mSearchParams.mField)
                        || SearchParams.SEARCH_FIELD_ALL.equals(mSearchParams.mField)));
        /// TCT: Only highlight un-empty subject
        if (fieldMatchedSubject && !TextUtils.isEmpty(subject)) {
            CharSequence subjectChars = TextUtilities.highlightTermsInText(subject, mSearchParams.mFilter);
            subjectToHighlight.replace(0, subject.length(), subjectChars);
        }/*from  ww  w  .  java  2s  . c o m*/
    }
    /// @}
    final Spannable displayedStringBuilder = new SpannableString(subjectToHighlight);

    // since spans affect text metrics, add spans to the string before measure/layout or fancy
    // ellipsizing

    final int badgeTextLength = formatBadgeText(displayedStringBuilder, badgeText);

    if (!TextUtils.isEmpty(subject)) {
        displayedStringBuilder.setSpan(
                TextAppearanceSpan.wrap(isUnread ? sSubjectTextUnreadSpan : sSubjectTextReadSpan),
                badgeTextLength, subject.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    if (isActivated() && showActivatedText()) {
        displayedStringBuilder.setSpan(sActivatedTextSpan, badgeTextLength, displayedStringBuilder.length(),
                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    }

    final int subjectWidth = mSubjectWidth;//TS: yanhua.chen 2015-9-2 EMAIL CR_540046 MOD
    final int subjectHeight = mCoordinates.subjectHeight;
    mSubjectTextView.setLayoutParams(new ViewGroup.LayoutParams(subjectWidth, subjectHeight));
    mSubjectTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mCoordinates.subjectFontSize);
    layoutViewExactly(mSubjectTextView, subjectWidth, subjectHeight);

    //[FEATURE]-Mod-BEGIN by CDTS.zhonghua.tuo,05/29/2014,FR 670064
    SpannableStringBuilder builder = new SpannableStringBuilder();
    boolean filterSubject = false;
    if (mField == UIProvider.LOCAL_SEARCH_ALL || mField == UIProvider.LOCAL_SEARCH_SUBJECT) {
        filterSubject = true;
    }
    if (mQueryText != null && filterSubject) {
        CharSequence formatSubject = displayedStringBuilder;
        formatSubject = TextUtilities.highlightTermsInText(subject, mQueryText);
        builder.append(formatSubject);
        mSubjectTextView.setText(builder);
        // TS: chao.zhang 2015-09-14 EMAIL FEATURE-585337 ADD_S
        //store the displayed subject for calculate the statusView's X and width
        mHeader.subjectText = builder.toString();
        // TS: chao.zhang 2015-09-14 EMAIL FEATURE-585337 ADD_E
    } else {
        mSubjectTextView.setText(displayedStringBuilder);
        // TS: chao.zhang 2015-09-14 EMAIL FEATURE-585337 ADD_S
        mHeader.subjectText = displayedStringBuilder.toString();
        // TS: chao.zhang 2015-09-14 EMAIL FEATURE-585337 ADD_E
    }
    //[FEATURE]-Mod-END by CDTS.zhonghua.tuo
}

From source file:com.android.launcher3.Utilities.java

/**
 * Wraps a message with a TTS span, so that a different message is spoken than
 * what is getting displayed.//from   ww  w  . ja va  2 s.c om
 * @param msg original message
 * @param ttsMsg message to be spoken
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static CharSequence wrapForTts(CharSequence msg, String ttsMsg) {
    if (Utilities.ATLEAST_LOLLIPOP) {
        SpannableString spanned = new SpannableString(msg);
        spanned.setSpan(new TtsSpan.TextBuilder(ttsMsg).build(), 0, spanned.length(),
                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        return spanned;
    } else {
        return msg;
    }
}

From source file:github.daneren2005.dsub.fragments.SelectDirectoryFragment.java

private void setupTextDisplay(final View header) {
    final TextView titleView = (TextView) header.findViewById(R.id.select_album_title);
    if (playlistName != null) {
        titleView.setText(playlistName);
    } else if (podcastName != null) {
        titleView.setText(podcastName);/*from  ww  w  .  j  av a 2  s .c o m*/
        titleView.setPadding(0, 6, 4, 8);
    } else if (name != null) {
        titleView.setText(name);

        if (artistInfo != null) {
            titleView.setPadding(0, 6, 4, 8);
        }
    } else if (share != null) {
        titleView.setVisibility(View.GONE);
    }

    int songCount = 0;

    Set<String> artists = new HashSet<String>();
    Set<Integer> years = new HashSet<Integer>();
    Integer totalDuration = 0;
    for (Entry entry : entries) {
        if (!entry.isDirectory()) {
            songCount++;
            if (entry.getArtist() != null) {
                artists.add(entry.getArtist());
            }
            if (entry.getYear() != null) {
                years.add(entry.getYear());
            }
            Integer duration = entry.getDuration();
            if (duration != null) {
                totalDuration += duration;
            }
        }
    }

    final TextView artistView = (TextView) header.findViewById(R.id.select_album_artist);
    if (podcastDescription != null || artistInfo != null) {
        artistView.setVisibility(View.VISIBLE);
        String text = podcastDescription != null ? podcastDescription : artistInfo.getBiography();
        Spanned spanned = null;
        if (text != null) {
            spanned = Html.fromHtml(text);
        }
        artistView.setText(spanned);
        artistView.setSingleLine(false);
        final int minLines = context.getResources().getInteger(R.integer.TextDescriptionLength);
        artistView.setLines(minLines);
        artistView.setTextAppearance(context, android.R.style.TextAppearance_Small);

        final Spanned spannedText = spanned;
        artistView.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                if (artistView.getMaxLines() == minLines) {
                    // Use LeadingMarginSpan2 to try to make text flow around image
                    Display display = context.getWindowManager().getDefaultDisplay();
                    ImageView coverArtView = (ImageView) header.findViewById(R.id.select_album_art);
                    coverArtView.measure(display.getWidth(), display.getHeight());

                    int height, width;
                    ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) coverArtView
                            .getLayoutParams();
                    if (coverArtView.getDrawable() != null) {
                        height = coverArtView.getMeasuredHeight() + coverArtView.getPaddingBottom();
                        width = coverArtView.getWidth() + coverArtView.getPaddingRight();
                    } else {
                        height = coverArtView.getHeight();
                        width = coverArtView.getWidth() + coverArtView.getPaddingRight();
                    }
                    float textLineHeight = artistView.getPaint().getTextSize();
                    int lines = (int) Math.ceil(height / textLineHeight);

                    SpannableString ss = new SpannableString(spannedText);
                    ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    View linearLayout = header.findViewById(R.id.select_album_text_layout);
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linearLayout
                            .getLayoutParams();
                    int[] rules = params.getRules();
                    rules[RelativeLayout.RIGHT_OF] = 0;
                    params.leftMargin = vlp.rightMargin;

                    artistView.setText(ss);
                    artistView.setMaxLines(100);

                    vlp = (ViewGroup.MarginLayoutParams) titleView.getLayoutParams();
                    vlp.leftMargin = width;
                } else {
                    artistView.setMaxLines(minLines);
                }
            }
        });
        artistView.setMovementMethod(LinkMovementMethod.getInstance());
    } else if (topTracks) {
        artistView.setText(R.string.menu_top_tracks);
        artistView.setVisibility(View.VISIBLE);
    } else if (showAll) {
        artistView.setText(R.string.menu_show_all);
        artistView.setVisibility(View.VISIBLE);
    } else if (artists.size() == 1) {
        String artistText = artists.iterator().next();
        if (years.size() == 1) {
            artistText += " - " + years.iterator().next();
        }
        artistView.setText(artistText);
        artistView.setVisibility(View.VISIBLE);
    } else {
        artistView.setVisibility(View.GONE);
    }

    TextView songCountView = (TextView) header.findViewById(R.id.select_album_song_count);
    TextView songLengthView = (TextView) header.findViewById(R.id.select_album_song_length);
    if (podcastDescription != null || artistInfo != null) {
        songCountView.setVisibility(View.GONE);
        songLengthView.setVisibility(View.GONE);
    } else {
        String s = context.getResources().getQuantityString(R.plurals.select_album_n_songs, songCount,
                songCount);
        songCountView.setText(s.toUpperCase());
        songLengthView.setText(Util.formatDuration(totalDuration));
    }
}

From source file:com.android.contacts.common.list.ContactListItemView.java

public void setDisplayName(CharSequence name) {
    if (!TextUtils.isEmpty(name)) {
        // Chooses the available highlighting method for highlighting.
        if (mHighlightedPrefix != null) {
            name = mTextHighlighter.applyPrefixHighlight(name, mHighlightedPrefix);
        } else if (mNameHighlightSequence.size() != 0) {
            final SpannableString spannableName = new SpannableString(name);
            for (HighlightSequence highlightSequence : mNameHighlightSequence) {
                mTextHighlighter.applyMaskingHighlight(spannableName, highlightSequence.start,
                        highlightSequence.end);
            }/* w ww.ja  va2 s .  c  o  m*/
            name = spannableName;
        }
    } else {
        name = mUnknownNameText;
    }
    setMarqueeText(getNameTextView(), name);

    if (ContactDisplayUtils.isPossiblePhoneNumber(name)) {
        // Give the text-to-speech engine a hint that it's a phone number
        mNameTextView.setTextDirection(View.TEXT_DIRECTION_LTR);
        mNameTextView.setContentDescription(PhoneNumberUtilsCompat.createTtsSpannable(name.toString()));
    } else {
        // Remove span tags of highlighting for talkback to avoid reading highlighting and rest
        // of the name into two separate parts.
        mNameTextView.setContentDescription(name.toString());
    }
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

private void showIncomingNotification() {
    Intent intent = new Intent(this, VoIPActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    Notification.Builder builder = new Notification.Builder(this)
            .setContentTitle(LocaleController.getString("VoipInCallBranding", R.string.VoipInCallBranding))
            .setContentText(ContactsController.formatName(user.first_name, user.last_name))
            .setSmallIcon(R.drawable.notification)
            .setContentIntent(PendingIntent.getActivity(this, 0, intent, 0));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        endHash = Utilities.random.nextInt();
        Intent endIntent = new Intent();
        endIntent.setAction(getPackageName() + ".DECLINE_CALL");
        endIntent.putExtra("end_hash", endHash);
        CharSequence endTitle = LocaleController.getString("VoipDeclineCall", R.string.VoipDeclineCall);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            endTitle = new SpannableString(endTitle);
            ((SpannableString) endTitle).setSpan(new ForegroundColorSpan(0xFFF44336), 0, endTitle.length(), 0);
        }/*from  ww  w . j  a  va2s  . c  o  m*/
        builder.addAction(R.drawable.ic_call_end_white_24dp, endTitle,
                PendingIntent.getBroadcast(this, 0, endIntent, PendingIntent.FLAG_UPDATE_CURRENT));
        Intent answerIntent = new Intent();
        answerIntent.setAction(getPackageName() + ".ANSWER_CALL");
        answerIntent.putExtra("end_hash", endHash);
        CharSequence answerTitle = LocaleController.getString("VoipAnswerCall", R.string.VoipAnswerCall);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            answerTitle = new SpannableString(answerTitle);
            ((SpannableString) answerTitle).setSpan(new ForegroundColorSpan(0xFF00AA00), 0,
                    answerTitle.length(), 0);
        }
        builder.addAction(R.drawable.ic_call_white_24dp, answerTitle,
                PendingIntent.getBroadcast(this, 0, answerIntent, PendingIntent.FLAG_UPDATE_CURRENT));
        builder.setPriority(Notification.PRIORITY_MAX);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        builder.setShowWhen(false);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setColor(0xff2ca5e0);
        builder.setVibrate(new long[0]);
        builder.setCategory(Notification.CATEGORY_CALL);
        builder.setFullScreenIntent(PendingIntent.getActivity(this, 0, intent, 0), true);
    }
    if (user.photo != null) {
        TLRPC.FileLocation photoPath = user.photo.photo_small;
        if (photoPath != null) {
            BitmapDrawable img = ImageLoader.getInstance().getImageFromMemory(photoPath, null, "50_50");
            if (img != null) {
                builder.setLargeIcon(img.getBitmap());
            } else {
                try {
                    float scaleFactor = 160.0f / AndroidUtilities.dp(50);
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = scaleFactor < 1 ? 1 : (int) scaleFactor;
                    Bitmap bitmap = BitmapFactory
                            .decodeFile(FileLoader.getPathToAttach(photoPath, true).toString(), options);
                    if (bitmap != null) {
                        builder.setLargeIcon(bitmap);
                    }
                } catch (Throwable e) {
                    FileLog.e(e);
                }
            }
        }
    }
    Notification incomingNotification = builder.getNotification();
    startForeground(ID_INCOMING_CALL_NOTIFICATION, incomingNotification);
}

From source file:github.popeen.dsub.fragments.SelectDirectoryFragment.java

private void setupTextDisplay(final View header) {

    final TextView titleView = (TextView) header.findViewById(R.id.select_album_title);
    if (playlistName != null) {
        titleView.setText(playlistName);
    } else if (podcastName != null) {
        Collections.reverse(entries);
        titleView.setText(podcastName);// w w  w  .j  a  v a2s  . com
        titleView.setPadding(0, 6, 4, 8);
    } else if (name != null) {
        titleView.setText(name);
        if (artistInfo != null) {
            titleView.setPadding(0, 6, 4, 8);
        }
    } else if (share != null) {
        titleView.setVisibility(View.GONE);
    }

    int songCount = 0;

    Set<String> artists = new HashSet<String>();
    Set<Integer> years = new HashSet<Integer>();
    totalDuration = 0;
    for (Entry entry : entries) {
        if (!entry.isDirectory()) {
            songCount++;
            if (entry.getArtist() != null) {
                artists.add(entry.getArtist());
            }
            if (entry.getYear() != null) {
                years.add(entry.getYear());
            }
            Integer duration = entry.getDuration();
            if (duration != null) {
                totalDuration += duration;
            }
        }
    }
    String artistName = "";
    bookDescription = "Could not collect any info about the book at this time";
    try {

        artistName = artists.iterator().next();
        String endpoint = "getBookDirectory";
        if (Util.isTagBrowsing(context)) {
            endpoint = "getBook";
        }
        SharedPreferences prefs = Util.getPreferences(context);
        String url = Util.getRestUrl(context, endpoint) + "&id=" + directory.getId() + "&f=json";

        Log.w("GetInfo", url);
        String artist, title;
        int year = 0;
        artist = title = "";

        try {
            artist = artists.iterator().next();
        } catch (Exception e) {
            Log.w("GetInfoArtist", e.toString());
        }
        try {
            title = titleView.getText().toString();
        } catch (Exception e) {
            Log.w("GetInfoTitle", e.toString());
        }
        try {
            year = years.iterator().next();
        } catch (Exception e) {
            Log.w("GetInfoYear", e.toString());
        }

        BookInfoAPIParams params = new BookInfoAPIParams(url, artist, title, year);
        bookInfo = new BookInfoAPI(context).execute(params).get();
        bookDescription = bookInfo[0];
        bookReader = bookInfo[1];

    } catch (Exception e) {
        Log.w("GetInfoError", e.toString());
    }
    if (bookDescription.equals("noInfo")) {
        bookDescription = "The server has no description for this book";
    }

    final TextView artistView = (TextView) header.findViewById(R.id.select_album_artist);
    if (podcastDescription != null || artistInfo != null || bookDescription != null) {
        artistView.setVisibility(View.VISIBLE);

        String text = "";
        if (bookDescription != null) {
            text = bookDescription;
        }
        if (podcastDescription != null) {
            text = podcastDescription;
        }
        if (artistInfo != null) {
            text = artistInfo.getBiography();
        }
        Spanned spanned = null;
        if (text != null) {
            String newText = "";
            try {
                if (!artistName.equals("")) {
                    newText += "<b>" + context.getResources().getString(R.string.main_artist) + "</b>: "
                            + artistName + "<br/>";
                }
            } catch (Exception e) {
            }
            try {
                if (totalDuration > 0) {
                    newText += "<b>" + context.getResources().getString(R.string.album_book_reader) + "</b>: "
                            + bookReader + "<br/>";
                }
            } catch (Exception e) {
            }
            try {
                if (totalDuration > 0) {
                    newText += "<b>" + context.getResources().getString(R.string.album_book_length) + "</b>: "
                            + Util.formatDuration(totalDuration) + "<br/>";
                }
            } catch (Exception e) {
            }
            try {
                newText += text + "<br/>";
            } catch (Exception e) {
            }
            spanned = Html.fromHtml(newText);
        }

        artistView.setText(spanned);
        artistView.setSingleLine(false);
        final int minLines = context.getResources().getInteger(R.integer.TextDescriptionLength);
        artistView.setLines(minLines);
        artistView.setTextAppearance(context, android.R.style.TextAppearance_Small);

        final Spanned spannedText = spanned;
        artistView.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                if (artistView.getMaxLines() == minLines) {
                    // Use LeadingMarginSpan2 to try to make text flow around image
                    Display display = context.getWindowManager().getDefaultDisplay();
                    ImageView coverArtView = (ImageView) header.findViewById(R.id.select_album_art);
                    coverArtView.measure(display.getWidth(), display.getHeight());

                    int height, width;
                    ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) coverArtView
                            .getLayoutParams();
                    if (coverArtView.getDrawable() != null) {
                        height = coverArtView.getMeasuredHeight() + coverArtView.getPaddingBottom();
                        width = coverArtView.getWidth() + coverArtView.getPaddingRight();
                    } else {
                        height = coverArtView.getHeight();
                        width = coverArtView.getWidth() + coverArtView.getPaddingRight();
                    }
                    float textLineHeight = artistView.getPaint().getTextSize();

                    int lines = (int) Math.ceil(height / textLineHeight) + 1;

                    SpannableString ss = new SpannableString(spannedText);
                    ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    View linearLayout = header.findViewById(R.id.select_album_text_layout);
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linearLayout
                            .getLayoutParams();
                    int[] rules = params.getRules();
                    rules[RelativeLayout.RIGHT_OF] = 0;
                    params.leftMargin = vlp.rightMargin;

                    artistView.setText(ss);
                    artistView.setMaxLines(100);

                    vlp = (ViewGroup.MarginLayoutParams) titleView.getLayoutParams();
                    vlp.leftMargin = width;
                } else {
                    artistView.setMaxLines(minLines);
                }
            }
        });
        artistView.setMovementMethod(LinkMovementMethod.getInstance());
    } else if (topTracks) {
        artistView.setText(R.string.menu_top_tracks);
        artistView.setVisibility(View.VISIBLE);
    } else if (showAll) {
        artistView.setText(R.string.menu_show_all);
        artistView.setVisibility(View.VISIBLE);
    } else if (artists.size() == 1) {
        String artistText = artists.iterator().next();
        if (years.size() == 1) {
            artistText += " - " + years.iterator().next();
        }
        artistView.setText(artistText);
        artistView.setVisibility(View.VISIBLE);
    } else {
        artistView.setVisibility(View.GONE);
    }

    TextView songCountView = (TextView) header.findViewById(R.id.select_album_song_count);
    TextView songLengthView = (TextView) header.findViewById(R.id.select_album_song_length);
    if (podcastDescription != null || artistInfo != null) {
        songCountView.setVisibility(View.GONE);
        songLengthView.setVisibility(View.GONE);
    } else {
        String s = context.getResources().getQuantityString(R.plurals.select_album_n_songs, songCount,
                songCount);

        songCountView.setVisibility(View.GONE);
        songLengthView.setVisibility(View.GONE);
    }
}

From source file:com.Beat.RingdroidEditActivity.java

private void handleFatalError(final CharSequence errorInternalName, final CharSequence errorString,
        final Exception exception) {
    Log.i("Ringdroid", "handleFatalError");

    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
    int failureCount = prefs.getInt(PREF_ERROR_COUNT, 0);
    final SharedPreferences.Editor prefsEditor = prefs.edit();
    prefsEditor.putInt(PREF_ERROR_COUNT, failureCount + 1);
    prefsEditor.commit();/*from w  w  w. ja v  a 2 s  . c o m*/

    // Check if we already have a pref for whether or not we can
    // contact the server.
    int serverAllowed = prefs.getInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_UNKNOWN);

    if (serverAllowed == SERVER_ALLOWED_NO) {
        Log.i("Ringdroid", "ERR: SERVER_ALLOWED_NO");

        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    if (serverAllowed == SERVER_ALLOWED_YES) {
        Log.i("Ringdroid", "SERVER_ALLOWED_YES");

        new AlertDialog.Builder(RingdroidEditActivity.this).setTitle(R.string.alert_title_failure)
                .setMessage(errorString)
                .setPositiveButton(R.string.alert_ok_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        sendErrToServerAndFinish(errorInternalName, exception);
                        return;
                    }
                }).setCancelable(false).show();
        return;
    }

    // The number of times the user must have had a failure before
    // we'll ask them.  Defaults to 1, and each time they click "Later"
    // we double and add 1.
    final int allowServerCheckIndex = prefs.getInt(PREF_ERR_SERVER_CHECK, 1);
    if (failureCount < allowServerCheckIndex) {
        Log.i("Ringdroid", "failureCount " + failureCount + " is less than " + allowServerCheckIndex);
        // Just show a simple "write error" message
        showFinalAlert(exception, errorString);
        return;
    }

    final SpannableString message = new SpannableString(
            errorString + ". " + getResources().getText(R.string.error_server_prompt));
    Linkify.addLinks(message, Linkify.ALL);

    AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.alert_title_failure)
            .setMessage(message).setPositiveButton(R.string.server_yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_YES);
                    prefsEditor.commit();
                    sendErrToServerAndFinish(errorInternalName, exception);
                }
            }).setNeutralButton(R.string.server_later, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_CHECK, 1 + allowServerCheckIndex * 2);
                    Log.i("Ringdroid",
                            "Won't check again until " + (1 + allowServerCheckIndex * 2) + " errors.");
                    prefsEditor.commit();
                    finish();
                }
            }).setNegativeButton(R.string.server_never, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    prefsEditor.putInt(PREF_ERR_SERVER_ALLOWED, SERVER_ALLOWED_NO);
                    prefsEditor.commit();
                    finish();
                }
            }).setCancelable(false).show();

    // Make links clicky
    ((TextView) dialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:org.brandroid.openmanager.activities.OpenExplorer.java

@SuppressWarnings("unused")
public void updatePagerTitle(int page) {
    TextView tvLeft = null; // (TextView)findViewById(R.id.title_left);
    TextView tvRight = null; //(TextView)findViewById(R.id.title_right);
    String left = "";
    SpannableStringBuilder ssb = new SpannableStringBuilder();
    for (int i = 0; i < page; i++) {
        OpenFragment f = mViewPagerAdapter.getItem(i);
        if (f instanceof ContentFragment) {
            OpenPath p = ((ContentFragment) f).getPath();
            left += p.getName();//from  w  ww  .jav  a  2 s . co  m
            if (p.isDirectory() && !left.endsWith("/"))
                left += "/";
        }
    }
    SpannableString srLeft = new SpannableString(left);
    srLeft.setSpan(new ForegroundColorSpan(Color.GRAY), 0, left.length(), Spanned.SPAN_COMPOSING);
    ssb.append(srLeft);
    //ssb.setSpan(new ForegroundColorSpan(Color.GRAY), 0, left.length(), Spanned.SPAN_COMPOSING);
    OpenFragment curr = mViewPagerAdapter.getItem(page);
    if (curr instanceof ContentFragment) {
        OpenPath pCurr = ((ContentFragment) curr).getPath();
        ssb.append(pCurr.getName());
        if (pCurr.isDirectory())
            ssb.append("/");
    }
    String right = "";
    for (int i = page + 1; i < mViewPagerAdapter.getCount(); i++) {
        OpenFragment f = mViewPagerAdapter.getItem(i);
        if (f instanceof ContentFragment) {
            OpenPath p = ((ContentFragment) f).getPath();
            right += p.getName();
            if (p.isDirectory() && !right.endsWith("/"))
                right += "/";
        }
    }
    SpannableString srRight = new SpannableString(right);
    srRight.setSpan(new ForegroundColorSpan(Color.GRAY), 0, right.length(), Spanned.SPAN_COMPOSING);
    ssb.append(srRight);
    updateTitle(ssb);
}