Example usage for android.text SpannableString length

List of usage examples for android.text SpannableString length

Introduction

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

Prototype

int length();

Source Link

Document

Returns the length of this character sequence.

Usage

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  av a2s  .  c  om*/
        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:org.de.jmg.learn.SettingsActivity.java

public void init(boolean blnRestart) throws Exception {
    if (_Intent == null || _main == null || SettingsView == null || _blnInitialized) {
        return;/*  ww w. ja  v a2  s  .  c  om*/
    }
    try {
        //lib.ShowToast(_main, "Settings Start");

        RelativeLayout layout = (RelativeLayout) findViewById(R.id.layoutSettings); // id fetch from xml
        ShapeDrawable rectShapeDrawable = new ShapeDrawable(); // pre defined class
        int pxPadding = lib.dpToPx(10);
        rectShapeDrawable.setPadding(pxPadding, pxPadding, pxPadding,
                pxPadding * ((lib.NookSimpleTouch()) ? 2 : 1));
        Paint paint = rectShapeDrawable.getPaint();
        paint.setColor(Color.BLACK);
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(5); // you can change the value of 5
        lib.setBg(layout, rectShapeDrawable);

        mainView = _main.findViewById(Window.ID_ANDROID_CONTENT);
        //Thread.setDefaultUncaughtExceptionHandler(ErrorHandler);
        prefs = _main.getPreferences(Context.MODE_PRIVATE);

        TextView txtSettings = (TextView) findViewById(R.id.txtSettings);
        SpannableString Settings = new SpannableString(txtSettings.getText());
        Settings.setSpan(new UnderlineSpan(), 0, Settings.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        txtSettings.setText(Settings);
        initCheckBoxes();
        initSpinners(blnRestart);
        initButtons();
        initHelp();
        edDataDir = (EditText) findViewById(R.id.edDataDir);
        edDataDir.setSingleLine(true);
        edDataDir.setText(_main.JMGDataDirectory);
        edDataDir.setImeOptions(EditorInfo.IME_ACTION_DONE);
        edDataDir.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    String strDataDir = edDataDir.getText().toString();
                    File fileSelected = new File(strDataDir);
                    if (fileSelected.isDirectory() && fileSelected.exists()) {
                        _main.setJMGDataDirectory(fileSelected.getPath());
                        edDataDir.setText(_main.JMGDataDirectory);
                        Editor editor = prefs.edit();
                        editor.putString("JMGDataDirectory", fileSelected.getPath());
                        editor.commit();
                    }
                }
                return true;
            }
        });
        edDataDir.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ShowDataDirDialog();
                return true;
            }
        });
        if (!(lib.NookSimpleTouch()) && !_main.isSmallDevice) {
            SettingsView.getViewTreeObserver()
                    .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

                        @Override
                        public void onGlobalLayout() {
                            // Ensure you call it only once :
                            lib.removeLayoutListener(SettingsView.getViewTreeObserver(), this);

                            // Here you can get the size :)
                            resize(0);
                            //lib.ShowToast(_main, "Resize End");
                        }
                    });

        } else {
            //resize(1.8f);
            mScale = 1.0f;
        }
        _blnInitialized = true;
    } catch (Exception ex) {
        lib.ShowException(_main, ex);
    }

}

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  w  w w.ja  v a 2  s  . 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>();
    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

private void setMarqueeText(TextView textView, CharSequence text) {
    if (getTextEllipsis() == TruncateAt.MARQUEE) {
        // To show MARQUEE correctly (with END effect during non-active state), we need
        // to build Spanned with MARQUEE in addition to TextView's ellipsize setting.
        final SpannableString spannable = new SpannableString(text);
        spannable.setSpan(TruncateAt.MARQUEE, 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spannable);/*from   w ww.  j a  va2  s . c  om*/
    } else {
        textView.setText(text);
    }
}

From source file:com.heath_bar.tvdb.SeriesOverview.java

/** Populate the GUI with the episode information */
private void PopulateStuffPartTwo() {

    // Populate the next/last episodes
    TvEpisode last = episodeList.getLastAired();
    TvEpisode next = episodeList.getNextAired();

    SpannableString text = null;

    TextView richTextView = (TextView) findViewById(R.id.last_episode);

    if (last == null) {
        text = new SpannableString("Last Episode: unknown");
    } else {/*from w ww .j  av a2s. co m*/

        text = new SpannableString(
                "Last Episode: " + last.getName() + " (" + DateUtil.toString(last.getAirDate()) + ")");

        NonUnderlinedClickableSpan clickableSpan = new NonUnderlinedClickableSpan() {
            @Override
            public void onClick(View view) {
                episodeListener.onClick(view);
            }
        };
        int start = 14;
        int end = start + last.getName().length();
        text.setSpan(clickableSpan, start, end, 0);
        text.setSpan(new TextAppearanceSpan(this, R.style.episode_link), start, end, 0);
        text.setSpan(new AbsoluteSizeSpan((int) textSize, true), 0, text.length(), 0);
        richTextView.setId(last.getId());
        richTextView.setMovementMethod(LinkMovementMethod.getInstance());
    }
    richTextView.setText(text, BufferType.SPANNABLE);

    text = null;
    richTextView = (TextView) findViewById(R.id.next_episode);

    if (seriesInfo != null && seriesInfo.getStatus() != null && !seriesInfo.getStatus().equals("Ended")) {
        if (next == null) {
            text = new SpannableString("Next Episode: unknown");
        } else {

            text = new SpannableString(
                    "Next Episode: " + next.getName() + " (" + DateUtil.toString(next.getAirDate()) + ")");

            NonUnderlinedClickableSpan clickableSpan = new NonUnderlinedClickableSpan() {
                @Override
                public void onClick(View view) {
                    episodeListener.onClick(view);
                }
            };
            int start = 14;
            int end = start + next.getName().length();
            text.setSpan(clickableSpan, start, end, 0);
            text.setSpan(new TextAppearanceSpan(this, R.style.episode_link), start, end, 0);
            text.setSpan(new AbsoluteSizeSpan((int) textSize, true), 0, text.length(), 0);
            richTextView.setId(next.getId());
            richTextView.setMovementMethod(LinkMovementMethod.getInstance());
        }
        richTextView.setText(text, BufferType.SPANNABLE);
    }
}

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);//from   w  w w .j  a  v a2  s.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.android.mail.browse.ConversationItemView.java

SpannableStringBuilder elideParticipants(List<SpannableString> parts) {
    final SpannableStringBuilder builder = new SpannableStringBuilder();
    float totalWidth = 0;
    boolean ellipsize = false;
    float width;/*from   w  w w.  jav a2 s  . c om*/
    boolean skipToHeader = false;

    // start with "To: " if we're showing recipients
    if (mDisplayedFolder.shouldShowRecipients() && !parts.isEmpty()) {
        final SpannableString toHeader = SendersView.getFormattedToHeader();
        CharacterStyle[] spans = toHeader.getSpans(0, toHeader.length(), CharacterStyle.class);
        // There is only 1 character style span; make sure we apply all the
        // styles to the paint object before measuring.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        totalWidth += sPaint.measureText(toHeader.toString());
        builder.append(toHeader);
        skipToHeader = true;
    }

    final SpannableStringBuilder messageInfoString = mHeader.messageInfoString;
    if (!TextUtils.isEmpty(messageInfoString)) {
        CharacterStyle[] spans = messageInfoString.getSpans(0, messageInfoString.length(),
                CharacterStyle.class);
        // There is only 1 character style span; make sure we apply all the
        // styles to the paint object before measuring.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        // Paint the message info string to see if we lose space.
        float messageInfoWidth = sPaint.measureText(messageInfoString.toString());
        totalWidth += messageInfoWidth;
    }
    SpannableString prevSender = null;
    SpannableString ellipsizedText;
    for (SpannableString sender : parts) {
        // There may be null sender strings if there were dupes we had to remove.
        if (sender == null) {
            continue;
        }
        // No more width available, we'll only show fixed fragments.
        if (ellipsize) {
            break;
        }
        CharacterStyle[] spans = sender.getSpans(0, sender.length(), CharacterStyle.class);
        // There is only 1 character style span.
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        // If there are already senders present in this string, we need to
        // make sure we prepend the dividing token
        if (SendersView.sElidedString.equals(sender.toString())) {
            sender = copyStyles(spans, sElidedPaddingToken + sender + sElidedPaddingToken);
        } else if (!skipToHeader && builder.length() > 0
                && (prevSender == null || !SendersView.sElidedString.equals(prevSender.toString()))) {
            sender = copyStyles(spans, sSendersSplitToken + sender);
        } else {
            skipToHeader = false;
        }
        prevSender = sender;

        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        // Measure the width of the current sender and make sure we have space
        width = (int) sPaint.measureText(sender.toString());
        if (width + totalWidth > mSendersWidth) {
            // The text is too long, new line won't help. We have to
            // ellipsize text.
            ellipsize = true;
            width = mSendersWidth - totalWidth; // ellipsis width?
            ellipsizedText = copyStyles(spans, TextUtils.ellipsize(sender, sPaint, width, TruncateAt.END));
            width = (int) sPaint.measureText(ellipsizedText.toString());
        } else {
            ellipsizedText = null;
        }
        totalWidth += width;

        final CharSequence fragmentDisplayText;
        if (ellipsizedText != null) {
            fragmentDisplayText = ellipsizedText;
        } else {
            fragmentDisplayText = sender;
        }
        builder.append(fragmentDisplayText);
    }
    mHeader.styledMessageInfoStringOffset = builder.length();
    if (!TextUtils.isEmpty(messageInfoString)) {
        builder.append(messageInfoString);
    }
    return builder;
}

From source file:org.kiwix.kiwixmobile.KiwixMobileActivity.java

private SpannableString createMenuText(String title) {
    SpannableString s = new SpannableString(title);
    s.setSpan(new ForegroundColorSpan(Color.WHITE), 0, s.length(), 0);
    return s;//from  ww  w  .  j  a va 2 s.c  o m
}

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

public static void handlePriority(Context context, int maxChars, String messageInfoString,
        ConversationInfo conversationInfo, ArrayList<SpannableString> styledSenders,
        ArrayList<String> displayableSenderNames, ArrayList<String> displayableSenderEmails, String account,
        final TextAppearanceSpan unreadStyleSpan, final CharacterStyle readStyleSpan) {
    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 ww.  ja  v a  2  s  .co m

    final Map<Integer, Integer> priorityToLength = PRIORITY_LENGTH_MAP_CACHE.get();
    try {
        priorityToLength.clear();
        int senderLength;
        for (MessageInfo info : conversationInfo.messageInfos) {
            senderLength = !TextUtils.isEmpty(info.sender) ? info.sender.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
    MessageInfo currentMessage;
    SpannableString spannableDisplay;
    String nameString;
    CharacterStyle style;
    boolean appendedElided = false;
    Map<String, Integer> displayHash = Maps.newHashMap();
    String firstDisplayableSenderEmail = null;
    String firstDisplayableSender = null;
    for (int i = 0; i < conversationInfo.messageInfos.size(); i++) {
        currentMessage = conversationInfo.messageInfos.get(i);
        nameString = !TextUtils.isEmpty(currentMessage.sender) ? currentMessage.sender : "";
        if (nameString.length() == 0) {
            nameString = getMe(context);
        }
        if (numCharsToRemovePerWord != 0) {
            nameString = nameString.substring(0, Math.max(nameString.length() - numCharsToRemovePerWord, 0));
        }
        final int priority = currentMessage.priority;
        style = !currentMessage.read ? getWrappedStyleSpan(unreadStyleSpan)
                : getWrappedStyleSpan(readStyleSpan);
        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(currentMessage.sender) ? displayHash.get(currentMessage.sender)
                    : DOES_NOT_EXIST;
            // If this sender doesn't exist OR the current message is
            // unread, add the sender.
            if (oldPos == DOES_NOT_EXIST || !currentMessage.read) {
                // 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(currentMessage.senderEmail)) {
                        displayableSenderEmails.remove(currentMessage.senderEmail);
                        displayableSenderNames.remove(currentMessage.sender);
                    }
                }
                displayHash.put(currentMessage.sender, 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(currentMessage.sender) ? account
                    : TextUtils.isEmpty(currentMessage.senderEmail) ? currentMessage.sender
                            : currentMessage.senderEmail;
            if (i == 0) {
                // Always add the first sender!
                firstDisplayableSenderEmail = senderEmail;
                firstDisplayableSender = currentMessage.sender;
            } 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(currentMessage.sender);
                    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:org.kiwix.kiwixmobile.KiwixMobileActivity.java

private SpannableString createMenuItem(String title) {
    SpannableString s = new SpannableString(title);
    if (nightMode) {
        s.setSpan(new ForegroundColorSpan(Color.WHITE), 0, s.length(), 0);
    } else {//from  w  ww  . j  ava 2  s. c om
        s.setSpan(new ForegroundColorSpan(Color.BLACK), 0, s.length(), 0);
    }
    return s;
}