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: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  .j  a v a 2  s  .com*/

    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.android.mail.browse.SendersView.java

private static void handlePriority(int maxChars, String messageInfoString, ConversationInfo conversationInfo,
        ArrayList<SpannableString> styledSenders, ArrayList<String> displayableSenderNames,
        ConversationItemViewModel.SenderAvatarModel senderAvatarModel, Account account,
        final TextAppearanceSpan unreadStyleSpan, final CharacterStyle readStyleSpan,
        final boolean showToHeader) {
    final boolean shouldSelectSenders = displayableSenderNames != null;
    final boolean shouldSelectAvatar = senderAvatarModel != 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   ww w.  j  a  v  a2 s . 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);
    }

    SpannableString spannableDisplay;
    boolean appendedElided = false;
    final Map<String, Integer> displayHash = Maps.newHashMap();
    final List<String> senderEmails = Lists.newArrayListWithExpectedSize(MAX_SENDER_COUNT);
    String firstSenderEmail = null;
    String firstSenderName = null;
    for (int i = 0; i < conversationInfo.participantInfos.size(); i++) {
        final ParticipantInfo 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;
        final CharacterStyle 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 (shouldSelectSenders && !TextUtils.isEmpty(currentEmail)) {
                        senderEmails.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);
            }
        }

        final String senderEmail = TextUtils.isEmpty(currentName) ? account.getEmailAddress()
                : TextUtils.isEmpty(currentEmail) ? currentName : currentEmail;

        if (shouldSelectSenders) {
            if (i == 0) {
                // Always add the first sender!
                firstSenderEmail = senderEmail;
                firstSenderName = currentName;
            } else {
                if (!Objects.equal(firstSenderEmail, senderEmail)) {
                    int indexOf = senderEmails.indexOf(senderEmail);
                    if (indexOf > -1) {
                        senderEmails.remove(indexOf);
                        displayableSenderNames.remove(indexOf);
                    }
                    senderEmails.add(senderEmail);
                    displayableSenderNames.add(currentName);
                    if (senderEmails.size() > MAX_SENDER_COUNT) {
                        senderEmails.remove(0);
                        displayableSenderNames.remove(0);
                    }
                }
            }
        }

        // if the corresponding message from this participant is unread and no sender avatar
        // is yet chosen, choose this one
        if (shouldSelectAvatar && senderAvatarModel.isNotPopulated() && !currentParticipant.readConversation) {
            senderAvatarModel.populate(currentName, senderEmail);
        }
    }

    // always add the first sender to the display
    if (shouldSelectSenders && !TextUtils.isEmpty(firstSenderEmail)) {
        if (displayableSenderNames.size() < MAX_SENDER_COUNT) {
            displayableSenderNames.add(0, firstSenderName);
        } else {
            displayableSenderNames.set(0, firstSenderName);
        }
    }

    // if all messages in the thread were read, we must search for an appropriate avatar
    if (shouldSelectAvatar && senderAvatarModel.isNotPopulated()) {
        // search for the last sender that is not the current account
        for (int i = conversationInfo.participantInfos.size() - 1; i >= 0; i--) {
            final ParticipantInfo participant = conversationInfo.participantInfos.get(i);
            // empty name implies it is the current account and should not be chosen
            if (!TextUtils.isEmpty(participant.name)) {
                // use the participant name in place of unusable email addresses
                final String senderEmail = TextUtils.isEmpty(participant.email) ? participant.name
                        : participant.email;
                senderAvatarModel.populate(participant.name, senderEmail);
                break;
            }
        }

        // if we still don't have an avatar, the account is emailing itself
        if (senderAvatarModel.isNotPopulated()) {
            senderAvatarModel.populate(account.getDisplayName(), account.getEmailAddress());
        }
    }
}

From source file:org.de.jmg.learn._MainActivity.java

public void SetActionBarTitle() throws Exception {
    if (mainView == null)
        return;//from w  ww . jav  a2s. co  m
    if (_vok.getGesamtzahl() > 0) {
        String FName = "";
        if (!libString.IsNullOrEmpty(_vok.getFileName())) {
            FName = new File(_vok.getFileName()).getName();
        } else if (_vok.getURI() != null) {
            String path = lib.dumpUriMetaData(_main, _vok.getURI());
            if (path.contains(":"))
                path = path.split(":")[0];
            int li = path.lastIndexOf("/");
            if (li > -1) {
                FName = path.substring(path.lastIndexOf("/"));
            } else {
                FName = "/" + path;
            }
        } else if (!libString.IsNullOrEmpty(_vok.getURIName())) {
            FName = _vok.getURIName();
        }
        if (FName.length() > 15 && _isSmallDevice) {
            FName = FName.substring(0, 15);
        } else if (FName.length() > 30) {
            FName = FName.substring(0, 30);
        }
        String title = "" + FName + " " + getString(R.string.number) + ": " + _vok.getIndex() + "/"
                + (_vok.getVokabeln().size() - 1) + " " + getString(R.string.counter) + ": "
                + _vok.getZaehler();
        String Right = " " + _vok.AnzRichtig;
        String Wrong = " " + _vok.AnzFalsch;
        SpannableString spnTitle = new SpannableString(title);
        SpannableString spnRight = new SpannableString(Right);
        SpannableString spnWrong = new SpannableString(Wrong);
        spnRight.setSpan(new ForegroundColorSpan(Color.GREEN), 0, spnRight.length(),
                SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        spnWrong.setSpan(new ForegroundColorSpan(Color.RED), 0, spnWrong.length(),
                SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        TextView txtStatus = (TextView) (findViewById(R.id.txtStatus));
        if (txtStatus != null)
            txtStatus.setText(TextUtils.concat(spnTitle, spnRight, spnWrong));
        //getSupportActionBar().setTitle(
        //      TextUtils.concat(spnTitle, spnRight, spnWrong));

    } else {
        Log.d("Vok", "empty");
        /*
         * String title = "Learn " + "empty._vok" + " " +
         * getString(R.string.number) + ": " + _vok.getIndex() + " " +
         * getString(R.string.counter) + ": " + _vok.getZaehler(); String
         * Right = " " + _vok.AnzRichtig; String Wrong = " " + _vok.AnzFalsch;
         * SpannableString spnTitle = new SpannableString(title);
         * SpannableString spnRight = new SpannableString(Right);
         * SpannableString spnWrong = new SpannableString(Wrong);
         * spnRight.setSpan(new ForegroundColorSpan(Color.GREEN), 0,
         * spnRight.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
         * spnWrong.setSpan(new ForegroundColorSpan(Color.RED), 0,
         * spnWrong.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
         *
         * getSupportActionBar().setTitle( TextUtils.concat(spnTitle,
         * spnRight, spnWrong));
         */
    }
    resizeActionbar(0);
}

From source file:org.de.jmg.learn._MainActivity.java

public void getVokabel(final boolean showBeds, boolean LoadNext, boolean requestFocusEdWord, boolean DontPrompt)
        throws Exception {

    if (iv != null) {
        iv.setVisibility(View.GONE);
    }/*from  ww w .j a v  a2 s.c  om*/
    if (iv2 != null)
        iv2.setVisibility(View.GONE);
    try {
        if (_btnRight == null)
            return;
        EndEdit(DontPrompt);
        setBtnsEnabled(true);
        if (showBeds && _vok.getIndex() >= 1) {
            _btnRight.setEnabled(true);
            _btnWrong.setEnabled(true);
            _btnEdit.setEnabled(true);
            _btnSkip.setEnabled(true);
            _btnView.setEnabled(true);
        } else {
            _btnRight.setEnabled(false);
            _btnWrong.setEnabled(false);
            if (_vok.getIndex() < 1) {
                _btnEdit.setEnabled(false);
                _btnSkip.setEnabled(false);
                _btnView.setEnabled(false);
            }
        }
        if (LoadNext)
            _vok.setLernIndex((short) (_vok.getLernIndex() + 1));

        View v;
        TextView t;
        String txtBed = getString(R.string.cloze);

        if (showBeds) {
            v = findViewById(R.id.txtMeaning1);
            t = (TextView) v;
            assert t != null;
            t.setText(lib.getSpanableString(_vok.getBedeutung1()));
            txtBed = t.getText().toString();
        }

        v = findViewById(R.id.word);
        t = (TextView) v;
        assert t != null;
        String txtWord = getString(R.string.cloze);
        if (!_vok.reverse || showBeds) {
            t.setText(lib.getSpanableString(_vok.getWort()), TextView.BufferType.SPANNABLE);
            txtWord = t.getText().toString();
            txtWord = replaceClozes(txtWord, txtBed);
            speak(txtWord, _vok.getLangWord(), "word", true);
        } else {
            t.setText("");
        }

        if (_vok.getSprache() == EnumSprachen.Hebrew || _vok.getSprache() == EnumSprachen.Griechisch
                || (_vok.getFontWort().getName().equalsIgnoreCase("Cardo"))) {
            t.setTypeface(_vok.TypefaceCardo);
            _txtedWord.setTypeface(_vok.TypefaceCardo);
        } else {
            t.setTypeface(Typeface.DEFAULT);
            _txtedWord.setTypeface(Typeface.DEFAULT);
        }
        t.scrollTo(0, 0);

        v = findViewById(R.id.Comment);
        t = (TextView) v;
        assert t != null;
        t.setVisibility(View.VISIBLE);

        SpannableString tspanKom = lib.getSpanableString(_vok.getKommentar());
        URLSpan[] urlSpans = tspanKom.getSpans(0, tspanKom.length(), URLSpan.class);
        for (final URLSpan span : urlSpans) {
            int start = tspanKom.getSpanStart(span);
            int end = tspanKom.getSpanEnd(span);
            String txt = tspanKom.toString().substring(start, end);
            if (txtIsPicture(txt)) {
                tspanKom.removeSpan(span);
                tspanKom.setSpan(new urlclickablespan(span.getURL()) {
                    @Override
                    public void onClick(View widget) {
                        Bitmap b;
                        try {
                            b = lib.downloadpicture(this.url);
                        } catch (Exception ex) {
                            b = null;
                        }
                        if (b != null) {
                            if (iv == null) {
                                iv = new ImageView(context);
                                SetTouchListener(iv);
                            }
                            b = resizeBM(b);
                            iv.setImageBitmap(b);
                            if (iv.getParent() == null) {
                                try {
                                    LayoutParams p = _txtMeaning1.getLayoutParams();
                                    //p.width = LayoutParams.WRAP_CONTENT;
                                    //p.height = LayoutParams.WRAP_CONTENT;
                                    rellayoutMain.addView(iv, p);
                                } catch (Exception ex) {
                                    Log.e("addImageView", ex.getMessage(), ex);
                                }
                            } else {
                                Log.d("ImageView", "exists");
                            }
                            _txtMeaning1.setVisibility(View.GONE);
                            iv.setVisibility(View.VISIBLE);
                        }
                    }
                }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        t.setText(tspanKom, TextView.BufferType.SPANNABLE);

        if (_vok.getSprache() == EnumSprachen.Hebrew || _vok.getSprache() == EnumSprachen.Griechisch
                || (_vok.getFontKom().getName().equalsIgnoreCase("Cardo"))) {
            t.setTypeface(_vok.TypefaceCardo);
            _txtedKom.setTypeface(_vok.TypefaceCardo);
        } else {
            t.setTypeface(Typeface.DEFAULT);
            _txtedKom.setTypeface(Typeface.DEFAULT);
        }
        if (_isSmallDevice && libString.IsNullOrEmpty(t.getText().toString())) {
            t.setVisibility(View.GONE);
        } else {
            t.setVisibility(View.VISIBLE);
        }
        t.scrollTo(0, 0);

        v = findViewById(R.id.txtMeaning1);
        t = (TextView) v;
        assert t != null;
        if (!libString.IsNullOrEmpty(_vok.getBedeutung2())) {
            t.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        }
        if (_vok.reverse || showBeds) {
            SpannableString tspan = lib.getSpanableString(_vok.getBedeutung1());
            //final String picname = _main.getString(R.string.picture);
            t.setVisibility(View.VISIBLE);
            if (txtIsPicture(tspan.toString())) {
                URLSpan urlspn[] = tspan.getSpans(0, tspan.length(), URLSpan.class);
                for (URLSpan url : urlspn) {
                    Bitmap b;
                    try {
                        b = lib.downloadpicture(url.getURL());
                    } catch (Exception ex) {
                        b = null;
                    }
                    if (b != null) {
                        if (iv == null) {
                            iv = new ImageView(context);
                            SetTouchListener(iv);
                        }
                        b = resizeBM(b);
                        iv.setImageBitmap(b);
                        if (iv.getParent() == null) {
                            try {
                                LayoutParams p = t.getLayoutParams();
                                //p.width = LayoutParams.WRAP_CONTENT;
                                //p.height = LayoutParams.WRAP_CONTENT;
                                rellayoutMain.addView(iv, p);
                            } catch (Exception ex) {
                                Log.e("Imagview", ex.getMessage(), ex);
                            }
                        } else {
                            Log.d("ImageView", "exists");
                        }
                        t.setVisibility(View.GONE);
                        iv.setVisibility(View.VISIBLE);
                    }
                }

            } else {
                // iv.setVisibility(View.GONE);
                t.setVisibility(View.VISIBLE);
            }

            t.setText(tspan);
        } else {
            t.setText(Vokabel.getComment(_vok.getBedeutung1()));
        }
        if (_vok.reverse || showBeds) {
            String txt = t.getText().toString();
            txt = replaceClozes(txt, txtWord);
            speak(txt, _vok.getLangMeaning(), "meaning1", _vok.reverse);
        }
        if (_vok.getFontBed().getName().equalsIgnoreCase("Cardo")) {
            t.setTypeface(_vok.TypefaceCardo);
        } else {
            t.setTypeface(Typeface.DEFAULT);
        }
        t.setOnFocusChangeListener(FocusListenerMeaning1);
        t.scrollTo(0, 0);

        v = findViewById(R.id.txtMeaning2);
        t = (TextView) v;
        assert t != null;
        t.setText((_vok.reverse || showBeds ? _vok.getBedeutung2() : Vokabel.getComment(_vok.getBedeutung2())));
        if (_vok.getFontBed().getName().equalsIgnoreCase("Cardo")) {
            t.setTypeface(_vok.TypefaceCardo);
        } else {
            t.setTypeface(Typeface.DEFAULT);
        }
        if (libString.IsNullOrEmpty(_vok.getBedeutung2()) || _vok.getCardMode()) {
            t.setVisibility(View.GONE);
            _txtMeaning1.setImeOptions(EditorInfo.IME_ACTION_DONE);
        } else {
            t.setVisibility(View.VISIBLE);
            _txtMeaning1.setImeOptions(EditorInfo.IME_ACTION_NEXT);
            if (_vok.reverse || showBeds) {
                String txt = t.getText().toString();
                //if (txtWord != null)
                //   txt = txt.replaceAll("_{2,}", txtWord).replaceAll("\\.{4,}", txtWord);
                speak(txt, _vok.getLangMeaning(), "meaning2");
            }
        }

        v = findViewById(R.id.txtMeaning3);
        t = (TextView) v;
        assert t != null;
        t.setText((_vok.reverse || showBeds ? _vok.getBedeutung3() : Vokabel.getComment(_vok.getBedeutung3())));
        if (_vok.getFontBed().getName().equalsIgnoreCase("Cardo")) {
            t.setTypeface(_vok.TypefaceCardo);
        } else {
            t.setTypeface(Typeface.DEFAULT);
        }
        if (libString.IsNullOrEmpty(_vok.getBedeutung3()) || _vok.getCardMode()) {
            t.setVisibility(View.GONE);
            _txtMeaning2.setImeOptions(EditorInfo.IME_ACTION_DONE);
        } else {
            t.setVisibility(View.VISIBLE);
            _txtMeaning2.setImeOptions(EditorInfo.IME_ACTION_NEXT);
            _txtMeaning3.setImeOptions(EditorInfo.IME_ACTION_DONE);
            if (_vok.reverse || showBeds) {
                String txt = t.getText().toString();
                //if (txtWord != null)
                //   txt = txt.replaceAll("_{2,}", txtWord).replaceAll("\\.{4,}", txtWord);
                speak(txt, _vok.getLangMeaning(), "meaning3");
            }
        }

        if (_vok.reverse && showBeds)
            speak(txtWord, _vok.getLangWord(), "word");

        lib.setBgEditText(_txtMeaning1, _MeaningBG);
        lib.setBgEditText(_txtMeaning2, _MeaningBG);
        lib.setBgEditText(_txtMeaning3, _MeaningBG);
        if (!_isSmallDevice && !requestFocusEdWord) {
            _txtMeaning1.requestFocus();
        } else {
            if (!requestFocusEdWord)
                _txtWord.requestFocus();
            else
                _txtedWord.requestFocus();
        }
        SetActionBarTitle();

        _scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {

                lib.removeLayoutListener(_scrollView.getViewTreeObserver(), this);
                hideKeyboard();
                if (showBeds) {
                    _scrollView.scrollTo(0, _txtMeaning1.getTop());
                } else {
                    _txtWord.requestFocus();
                    _scrollView.fullScroll(View.FOCUS_UP);
                }
            }
        });

    } catch (Exception e) {

        lib.ShowException(_main, e);
    }

}

From source file:com.andrewshu.android.reddit.comments.CommentsListActivity.java

/**
 * Mark the OP submitter comments/*from w w  w  .  j a  v a2s .c o  m*/
 */
void markSubmitterComments() {
    if (getOpThingInfo() == null || mCommentsAdapter == null)
        return;

    SpannableString authorSS = new SpannableString(getOpThingInfo().getAuthor() + " [S]");
    ForegroundColorSpan fcs;
    if (Util.isLightTheme(mSettings.getTheme()))
        fcs = new ForegroundColorSpan(getResources().getColor(R.color.blue));
    else
        fcs = new ForegroundColorSpan(getResources().getColor(R.color.pale_blue));
    authorSS.setSpan(fcs, 0, authorSS.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    for (int i = 0; i < mCommentsAdapter.getCount(); i++) {
        ThingInfo ci = mCommentsAdapter.getItem(i);
        // if it's the OP, mark his name
        if (getOpThingInfo().getAuthor().equalsIgnoreCase(ci.getAuthor()))
            ci.setSSAuthor(authorSS);
    }
}

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

SpannableStringBuilder elideParticipants(List<SpannableString> parts) {
    final SpannableStringBuilder builder = new SpannableStringBuilder();
    float totalWidth = 0;
    boolean ellipsize = false;
    float width;//from   www .ja  va  2  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 (messageInfoString.length() > 0) {
        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())) {
            prevSender = sender;
            sender = copyStyles(spans, sElidedPaddingToken + sender + sElidedPaddingToken);
        } else if (!skipToHeader && builder.length() > 0
                && (prevSender == null || !SendersView.sElidedString.equals(prevSender.toString()))) {
            prevSender = sender;
            sender = copyStyles(spans, sSendersSplitToken + sender);
        } else {
            prevSender = sender;
            skipToHeader = false;
        }
        if (spans.length > 0) {
            spans[0].updateDrawState(sPaint);
        }
        //TS: yanhua.chen 2015-9-2 EMAIL CR_540046 MOD_S
        // Measure the width of the current sender and make sure we have space
        width = (int) sPaint.measureText(sender.toString());
        if (width + totalWidth > mCoordinates.sendersWidth) {
            // The text is too long, new line won't help. We have to
            // ellipsize text.
            ellipsize = true;
            width = mCoordinates.sendersWidth - totalWidth; // ellipsis width?
            ellipsizedText = copyStyles(spans, TextUtils.ellipsize(sender, sPaint, width, TruncateAt.END));
            width = (int) sPaint.measureText(ellipsizedText.toString());
        } else {
            ellipsizedText = null;
        }
        totalWidth += width;
        //TS: yanhua.chen 2015-9-2 EMAIL CR_540046 MOD_E

        //[FEATURE]-Add-BEGIN by CDTS.zhonghua.tuo,05/29/2014,FR 670064
        CharSequence fragmentDisplayText;
        if (ellipsizedText != null) {
            fragmentDisplayText = ellipsizedText;
        } else {
            fragmentDisplayText = sender;
        }
        boolean filterSender = false;
        if (mField == UIProvider.LOCAL_SEARCH_ALL || mField == UIProvider.LOCAL_SEARCH_FROM) {
            filterSender = true;
        }
        if (mQueryText != null && filterSender) {
            fragmentDisplayText = TextUtilities.highlightTermsInText(fragmentDisplayText.toString(),
                    mQueryText);
        }
        //[FEATURE]-Add-END by CDTS.zhonghua.tuo
        builder.append(fragmentDisplayText);
    }
    mHeader.styledMessageInfoStringOffset = builder.length();
    builder.append(messageInfoString);
    return builder;
}

From source file:com.android.ex.chips.RecipientEditTextView.java

void createMoreChipPlainText() {
    // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
    final Editable text = getText();
    int start = 0;
    int end = start;
    for (int i = 0; i < CHIP_LIMIT; i++) {
        end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
        start = end; // move to the next token and get its end.
    }//from  w w w.j  av  a  2  s  .co m
    // Now, count total addresses.
    start = 0;
    final int tokenCount = countTokens(text);
    final MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
    final SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
    chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    text.replace(end, text.length(), chipText);
    mMoreChip = moreSpan;
}

From source file:com.android.ex.chips.RecipientEditTextView.java

/**
 * Create the more chip. The more chip is text that replaces any chips that do not fit in the pre-defined available
 * space when the RecipientEditTextView loses focus.
 *//*from w  w  w  .j  a v  a 2 s  . c  o  m*/
// Visible for testing.
/* package */void createMoreChip() {
    if (mNoChips) {
        createMoreChipPlainText();
        return;
    }
    if (!mShouldShrink)
        return;
    final ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
    if (tempMore.length > 0)
        getSpannable().removeSpan(tempMore[0]);
    final DrawableRecipientChip[] recipients = getSortedRecipients();
    if (recipients == null || recipients.length <= CHIP_LIMIT) {
        mMoreChip = null;
        return;
    }
    final Spannable spannable = getSpannable();
    final int numRecipients = recipients.length;
    final int overage = numRecipients - CHIP_LIMIT;
    final MoreImageSpan moreSpan = createMoreSpan(overage);
    mRemovedSpans = new ArrayList<DrawableRecipientChip>();
    int totalReplaceStart = 0;
    int totalReplaceEnd = 0;
    final Editable text = getText();
    for (int i = numRecipients - overage; i < recipients.length; i++) {
        mRemovedSpans.add(recipients[i]);
        if (i == numRecipients - overage)
            totalReplaceStart = spannable.getSpanStart(recipients[i]);
        if (i == recipients.length - 1)
            totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
        if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
            final int spanStart = spannable.getSpanStart(recipients[i]);
            final int spanEnd = spannable.getSpanEnd(recipients[i]);
            recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
        }
        spannable.removeSpan(recipients[i]);
    }
    if (totalReplaceEnd < text.length())
        totalReplaceEnd = text.length();
    final int end = Math.max(totalReplaceStart, totalReplaceEnd);
    final int start = Math.min(totalReplaceStart, totalReplaceEnd);
    final SpannableString chipText = new SpannableString(text.subSequence(start, end));
    chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    text.replace(start, end, chipText);
    mMoreChip = moreSpan;
    // If adding the +more chip goes over the limit, resize accordingly.
    if (!isPhoneQuery() && getLineCount() > mMaxLines)
        setMaxLines(getLineCount());
}

From source file:com.android.mail.compose.ComposeActivity.java

private static void removeSpansOfType(SpannableString str, Class<?> cls) {
    for (Object span : str.getSpans(0, str.length(), cls)) {
        str.removeSpan(span);/*w w  w.j  av  a  2  s .c o  m*/
    }
}

From source file:com.ichi2.anki.AbstractFlashcardViewer.java

protected void updateScreenCounts() {
    if (mCurrentCard == null) {
        return;//from www . j  a  va  2 s  .  c o m
    }

    try {
        String[] title = getCol().getDecks().get(mCurrentCard.getDid()).getString("name").split("::");
        getSupportActionBar().setTitle(title[title.length - 1]);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    int[] counts = mSched.counts(mCurrentCard);

    int eta = mSched.eta(counts, false);
    getSupportActionBar()
            .setSubtitle(getResources().getQuantityString(R.plurals.reviewer_window_title, eta, eta));

    SpannableString newCount = new SpannableString(String.valueOf(counts[0]));
    SpannableString lrnCount = new SpannableString(String.valueOf(counts[1]));
    SpannableString revCount = new SpannableString(String.valueOf(counts[2]));
    if (mPrefHideDueCount) {
        revCount = new SpannableString("???");
    }

    switch (mSched.countIdx(mCurrentCard)) {
    case Card.TYPE_NEW:
        newCount.setSpan(new UnderlineSpan(), 0, newCount.length(), 0);
        break;
    case Card.TYPE_LRN:
        lrnCount.setSpan(new UnderlineSpan(), 0, lrnCount.length(), 0);
        break;
    case Card.TYPE_REV:
        revCount.setSpan(new UnderlineSpan(), 0, revCount.length(), 0);
        break;
    }

    mTextBarNew.setText(newCount);
    mTextBarLearn.setText(lrnCount);
    mTextBarReview.setText(revCount);
}