Example usage for android.text SpannableStringBuilder insert

List of usage examples for android.text SpannableStringBuilder insert

Introduction

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

Prototype

public SpannableStringBuilder insert(int where, CharSequence tb) 

Source Link

Usage

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

public static SpannableStringBuilder createMessageInfo(Context context, Conversation conv,
        final boolean resourceCachingRequired) {
    SpannableStringBuilder messageInfo = new SpannableStringBuilder();

    try {//w  w w  .ja  v a  2  s.  com
        final ConversationInfo conversationInfo = conv.conversationInfo;
        final int sendingStatus = conv.sendingState;
        boolean hasSenders = false;
        // This covers the case where the sender is "me" and this is a draft
        // message, which means this will only run once most of the time.
        for (ParticipantInfo p : conversationInfo.participantInfos) {
            if (!TextUtils.isEmpty(p.name)) {
                hasSenders = true;
                break;
            }
        }
        getSenderResources(context, resourceCachingRequired);
        final int count = conversationInfo.messageCount;
        final int draftCount = conversationInfo.draftCount;
        if (count > 1) {
            appendMessageInfo(messageInfo, Integer.toString(count),
                    CharacterStyle.wrap(conv.read ? sMessageInfoReadStyleSpan : sMessageInfoUnreadStyleSpan),
                    false, conv.read);
        }

        boolean appendSplitToken = hasSenders || count > 1;
        if (draftCount > 0) {
            final CharSequence draftText;
            if (draftCount == 1) {
                draftText = sDraftSingularString;
            } else {
                draftText = sDraftPluralString + String.format(sDraftCountFormatString, draftCount);
            }

            appendMessageInfo(messageInfo, draftText, sDraftsStyleSpan, appendSplitToken, conv.read);
        }

        final boolean showState = sendingStatus == UIProvider.ConversationSendingState.SENDING
                || sendingStatus == UIProvider.ConversationSendingState.RETRYING
                || sendingStatus == UIProvider.ConversationSendingState.SEND_ERROR;
        if (showState) {
            appendSplitToken |= draftCount > 0;

            final CharSequence statusText;
            final Object span;
            if (sendingStatus == UIProvider.ConversationSendingState.SENDING) {
                statusText = sSendingString;
                span = sSendingStyleSpan;
            } else if (sendingStatus == UIProvider.ConversationSendingState.RETRYING) {
                statusText = sSendingString;
                span = sSendingStyleSpan;
            } else {
                statusText = sFailedString;
                span = sFailedStyleSpan;
            }

            appendMessageInfo(messageInfo, statusText, span, appendSplitToken, conv.read);
        }

        // Prepend a space if we are showing other message info text.
        if (count > 1 || (draftCount > 0 && hasSenders) || showState) {
            messageInfo.insert(0, sMessageCountSpacerString);
        }
    } finally {
        if (!resourceCachingRequired) {
            clearResourceCache();
        }
    }

    return messageInfo;
}

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

public static SpannableStringBuilder createMessageInfo(Context context, Conversation conv,
        final boolean resourceCachingRequired) {
    SpannableStringBuilder messageInfo = new SpannableStringBuilder();

    try {// ww  w.jav a  2  s .  c o  m
        ConversationInfo conversationInfo = conv.conversationInfo;
        int sendingStatus = conv.sendingState;
        boolean hasSenders = false;
        // This covers the case where the sender is "me" and this is a draft
        // message, which means this will only run once most of the time.
        for (MessageInfo m : conversationInfo.messageInfos) {
            if (!TextUtils.isEmpty(m.sender)) {
                hasSenders = true;
                break;
            }
        }
        getSenderResources(context, resourceCachingRequired);
        if (conversationInfo != null) {
            int count = conversationInfo.messageCount;
            int draftCount = conversationInfo.draftCount;
            boolean showSending = sendingStatus == UIProvider.ConversationSendingState.SENDING;
            if (count > 1) {
                messageInfo.append(count + "");
            }
            messageInfo.setSpan(
                    CharacterStyle.wrap(conv.read ? sMessageInfoReadStyleSpan : sMessageInfoUnreadStyleSpan), 0,
                    messageInfo.length(), 0);
            if (draftCount > 0) {
                // If we are showing a message count or any draft text and there
                // is at least 1 sender, prepend the sending state text with a
                // comma.
                if (hasSenders || count > 1) {
                    messageInfo.append(sSendersSplitToken);
                }
                SpannableStringBuilder draftString = new SpannableStringBuilder();
                if (draftCount == 1) {
                    draftString.append(sDraftSingularString);
                } else {
                    draftString.append(sDraftPluralString + String.format(sDraftCountFormatString, draftCount));
                }
                draftString.setSpan(CharacterStyle.wrap(sDraftsStyleSpan), 0, draftString.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                messageInfo.append(draftString);
            }
            if (showSending) {
                // If we are showing a message count or any draft text, prepend
                // the sending state text with a comma.
                if (count > 1 || draftCount > 0) {
                    messageInfo.append(sSendersSplitToken);
                }
                SpannableStringBuilder sending = new SpannableStringBuilder();
                sending.append(sSendingString);
                sending.setSpan(sSendingStyleSpan, 0, sending.length(), 0);
                messageInfo.append(sending);
            }
            // Prepend a space if we are showing other message info text.
            if (count > 1 || (draftCount > 0 && hasSenders) || showSending) {
                messageInfo.insert(0, sMessageCountSpacerString);
            }
        }
    } finally {
        if (!resourceCachingRequired) {
            clearResourceCache();
        }
    }

    return messageInfo;
}

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

public static SpannableStringBuilder createMessageInfo(Context context, Conversation conv,
        final boolean resourceCachingRequired) {
    SpannableStringBuilder messageInfo = new SpannableStringBuilder();

    try {//w  ww. j  a  va  2 s .  c  om
        ConversationInfo conversationInfo = conv.conversationInfo;
        int sendingStatus = conv.sendingState;
        boolean hasSenders = false;
        // This covers the case where the sender is "me" and this is a draft
        // message, which means this will only run once most of the time.
        for (ParticipantInfo p : conversationInfo.participantInfos) {
            if (!TextUtils.isEmpty(p.name)) {
                hasSenders = true;
                break;
            }
        }
        getSenderResources(context, resourceCachingRequired);
        int count = conversationInfo.messageCount;
        int draftCount = conversationInfo.draftCount;
        if (count > 1) {
            messageInfo.append(count + "");
        }
        messageInfo.setSpan(
                CharacterStyle.wrap(conv.read ? sMessageInfoReadStyleSpan : sMessageInfoUnreadStyleSpan), 0,
                messageInfo.length(), 0);
        if (draftCount > 0) {
            // If we are showing a message count or any draft text and there
            // is at least 1 sender, prepend the sending state text with a
            // comma.
            if (hasSenders || count > 1) {
                messageInfo.append(sSendersSplitToken);
            }
            SpannableStringBuilder draftString = new SpannableStringBuilder();
            if (draftCount == 1) {
                draftString.append(sDraftSingularString);
            } else {
                draftString.append(sDraftPluralString)
                        .append(String.format(sDraftCountFormatString, draftCount));
            }
            draftString.setSpan(CharacterStyle.wrap(sDraftsStyleSpan), 0, draftString.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            messageInfo.append(draftString);
        }
        // TS: chao.zhang 2015-09-29 EMAIL FEATURE-585337 MOD_S
        //NOTE:currently,we DONOT show the status in senderView, with our ERGO,show the status on the side if Subject.diable it!!!
        //boolean showState = sendingStatus == UIProvider.ConversationSendingState.SENDING ||
        //        sendingStatus == UIProvider.ConversationSendingState.RETRYING ||
        //       sendingStatus == UIProvider.ConversationSendingState.SEND_ERROR;
        boolean showState = false;
        // TS: chao.zhang 2015-09-29 EMAIL FEATURE-585337 MOD_E
        if (showState) {
            // If we are showing a message count or any draft text, prepend
            // the sending state text with a comma.
            if (count > 1 || draftCount > 0) {
                messageInfo.append(sSendersSplitToken);
            }

            SpannableStringBuilder stateSpan = new SpannableStringBuilder();

            if (sendingStatus == UIProvider.ConversationSendingState.SENDING) {
                stateSpan.append(sSendingString);
                stateSpan.setSpan(sSendingStyleSpan, 0, stateSpan.length(), 0);
            } else if (sendingStatus == UIProvider.ConversationSendingState.RETRYING) {
                stateSpan.append(sQueuedString);
                stateSpan.setSpan(sQueuedStyleSpan, 0, stateSpan.length(), 0);
            } else if (sendingStatus == UIProvider.ConversationSendingState.SEND_ERROR) {
                stateSpan.append(sFailedString);
                stateSpan.setSpan(sFailedStyleSpan, 0, stateSpan.length(), 0);
            }
            messageInfo.append(stateSpan);
        }

        // Prepend a space if we are showing other message info text.
        if (count > 1 || (draftCount > 0 && hasSenders) || showState) {
            messageInfo.insert(0, sMessageCountSpacerString);
        }
    } finally {
        if (!resourceCachingRequired) {
            clearResourceCache();
        }
    }

    return messageInfo;
}

From source file:org.tlhInganHol.android.klingonassistant.EntryActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // TTS://from  www .  j a  va 2  s. c o m
    // Initialize text-to-speech. This is an asynchronous operation.
    // The OnInitListener (second argument) is called after initialization completes.
    // Log.d(TAG, "Initialising TTS");
    mTts = new TextToSpeech(this, this, // TextToSpeech.OnInitListener
            "org.tlhInganHol.android.klingonttsengine"); // Requires API 14.

    setDrawerContentView(R.layout.entry);
    Resources resources = getResources();

    JellyBeanSpanFixTextView entryTitle = (JellyBeanSpanFixTextView) findViewById(R.id.entry_title);
    JellyBeanSpanFixTextView entryText = (JellyBeanSpanFixTextView) findViewById(R.id.definition);

    // TODO: Save and restore bundle state to preserve links.

    Uri uri = getIntent().getData();
    // Log.d(TAG, "EntryActivity - uri: " + uri.toString());
    // TODO: Disable the "About" menu item if this is the "About" entry.
    mParentQuery = getIntent().getStringExtra(SearchManager.QUERY);

    // Retrieve the entry's data.
    // Note: managedQuery is deprecated since API 11.
    Cursor cursor = managedQuery(uri, KlingonContentDatabase.ALL_KEYS, null, null, null);
    KlingonContentProvider.Entry entry = new KlingonContentProvider.Entry(cursor, getBaseContext());

    // Handle alternative spellings here.
    if (entry.isAlternativeSpelling()) {
        // TODO: Immediate redirect to query in entry.getDefinition();
    }

    // Get the shared preferences.
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    // Set the entry's name (along with info like "slang", formatted in HTML).
    entryTitle.invalidate();
    boolean useKlingonFont = sharedPrefs.getBoolean(Preferences.KEY_KLINGON_FONT_CHECKBOX_PREFERENCE,
            /* default */false);
    Typeface klingonTypeface = KlingonAssistant.getKlingonFontTypeface(getBaseContext());
    if (useKlingonFont) {
        // Preference is set to display this in {pIqaD}!
        entryTitle.setTypeface(klingonTypeface);
        entryTitle.setText(entry.getEntryNameInKlingonFont());
    } else {
        // Boring transcription based on English (Latin) alphabet.
        entryTitle.setText(Html.fromHtml(entry.getFormattedEntryName(/* isHtml */true)));
    }
    mEntryName = entry.getEntryName();

    // Set the colour for the entry name depending on its part of speech.
    boolean useColours = sharedPrefs.getBoolean(Preferences.KEY_USE_COLOURS_CHECKBOX_PREFERENCE,
            /* default */true);
    if (useColours) {
        entryTitle.setTextColor(entry.getTextColor());
    }

    // Create the expanded definition.
    String pos = entry.getFormattedPartOfSpeech(/* isHtml */false);
    String expandedDefinition = pos + entry.getDefinition();

    // Show the German definition.
    String definition_DE = "";
    boolean displayGermanEntry = entry.shouldDisplayGerman();
    int germanDefinitionStart = -1;
    String germanDefinitionHeader = "\n" + resources.getString(R.string.label_german) + ": ";
    if (displayGermanEntry) {
        germanDefinitionStart = expandedDefinition.length();
        definition_DE = entry.getDefinition_DE();
        expandedDefinition += germanDefinitionHeader + definition_DE;
    }

    // Set the share intent.
    setShareEntryIntent(entry);

    // Show the basic notes.
    String notes = entry.getNotes();
    if (!notes.equals("")) {
        expandedDefinition += "\n\n" + notes;
    }

    // If this entry is hypothetical or extended canon, display warnings.
    if (entry.isHypothetical() || entry.isExtendedCanon()) {
        expandedDefinition += "\n\n";
        if (entry.isHypothetical()) {
            expandedDefinition += resources.getString(R.string.warning_hypothetical);
        }
        if (entry.isExtendedCanon()) {
            expandedDefinition += resources.getString(R.string.warning_extended_canon);
        }
    }

    // Show synonyms, antonyms, and related entries.
    String synonyms = entry.getSynonyms();
    String antonyms = entry.getAntonyms();
    String seeAlso = entry.getSeeAlso();
    if (!synonyms.equals("")) {
        expandedDefinition += "\n\n" + resources.getString(R.string.label_synonyms) + ": " + synonyms;
    }
    if (!antonyms.equals("")) {
        expandedDefinition += "\n\n" + resources.getString(R.string.label_antonyms) + ": " + antonyms;
    }
    if (!seeAlso.equals("")) {
        expandedDefinition += "\n\n" + resources.getString(R.string.label_see_also) + ": " + seeAlso;
    }

    // Display components if that field is not empty, unless we are showing an analysis link, in
    // which case we want to hide the components.
    boolean showAnalysis = entry.isSentence() || entry.isDerivative();
    String components = entry.getComponents();
    if (!components.equals("")) {
        // Treat the components column of inherent plurals and their
        // singulars differently than for other entries.
        if (entry.isInherentPlural()) {
            expandedDefinition += "\n\n"
                    + String.format(resources.getString(R.string.info_inherent_plural), components);
        } else if (entry.isSingularFormOfInherentPlural()) {
            expandedDefinition += "\n\n"
                    + String.format(resources.getString(R.string.info_singular_form), components);
        } else if (!showAnalysis) {
            // This is just a regular list of components.
            expandedDefinition += "\n\n" + resources.getString(R.string.label_components) + ": " + components;
        }
    }

    // Display plural information.
    if (!entry.isPlural() && !entry.isInherentPlural() && !entry.isPlural()) {
        if (entry.isBeingCapableOfLanguage()) {
            expandedDefinition += "\n\n" + resources.getString(R.string.info_being);
        } else if (entry.isBodyPart()) {
            expandedDefinition += "\n\n" + resources.getString(R.string.info_body);
        }
    }

    // If the entry is a useful phrase, link back to its category.
    if (entry.isSentence()) {
        String sentenceType = entry.getSentenceType();
        if (!sentenceType.equals("")) {
            // Put the query as a placeholder for the actual category.
            expandedDefinition += "\n\n" + resources.getString(R.string.label_category) + ": {"
                    + entry.getSentenceTypeQuery() + "}";
        }
    }

    // If the entry is a sentence, make a link to analyse its components.
    if (showAnalysis) {
        String analysisQuery = entry.getEntryName();
        if (!components.equals("")) {
            // Strip the brackets around each component so they won't be processed.
            analysisQuery += ":" + entry.getPartOfSpeech();
            int homophoneNumber = entry.getHomophoneNumber();
            if (homophoneNumber != -1) {
                analysisQuery += ":" + homophoneNumber;
            }
            analysisQuery += KlingonContentProvider.Entry.COMPONENTS_MARKER + components.replaceAll("[{}]", "");
        }
        expandedDefinition += "\n\n" + resources.getString(R.string.label_analyze) + ": {" + analysisQuery
                + "}";
    }

    // Show the examples.
    String examples = entry.getExamples();
    if (!examples.equals("")) {
        expandedDefinition += "\n\n" + resources.getString(R.string.label_examples) + ": " + examples;
    }

    // Show the source.
    String source = entry.getSource();
    if (!source.equals("")) {
        expandedDefinition += "\n\n" + resources.getString(R.string.label_sources) + ": " + source;
    }

    // If this is a verb (but not a prefix or suffix), show the transitivity information.
    String transitivity = "";
    if (entry.isVerb()
            && sharedPrefs.getBoolean(Preferences.KEY_SHOW_TRANSITIVITY_CHECKBOX_PREFERENCE, /* default */
                    true)) {
        // This is a verb and show transitivity preference is set to true.
        transitivity = entry.getTransitivityString();
    }
    int transitivityStart = -1;
    String transitivityHeader = "\n\n" + resources.getString(R.string.label_transitivity) + ": ";
    boolean showTransitivityInformation = !transitivity.equals("");
    if (showTransitivityInformation) {
        transitivityStart = expandedDefinition.length();
        expandedDefinition += transitivityHeader + transitivity;
    }

    // Show the hidden notes.
    String hiddenNotes = "";
    if (sharedPrefs.getBoolean(Preferences.KEY_SHOW_ADDITIONAL_INFORMATION_CHECKBOX_PREFERENCE, /* default */
            true)) {
        // Show additional information preference set to true.
        hiddenNotes = entry.getHiddenNotes();
    }
    int hiddenNotesStart = -1;
    String hiddenNotesHeader = "\n\n" + resources.getString(R.string.label_additional_information) + ": ";
    if (!hiddenNotes.equals("")) {
        hiddenNotesStart = expandedDefinition.length();
        expandedDefinition += hiddenNotesHeader + hiddenNotes;
    }

    // Format the expanded definition, including linkifying the links to other entries.
    float smallTextScale = (float) 0.8;
    SpannableStringBuilder ssb = new SpannableStringBuilder(expandedDefinition);
    int intermediateFlags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_INTERMEDIATE;
    int finalFlags = Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
    if (!pos.equals("")) {
        // Italicise the part of speech.
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, pos.length(), finalFlags);
    }
    if (displayGermanEntry) {
        // Reduce the size of the German definition.
        ssb.setSpan(new RelativeSizeSpan(smallTextScale), germanDefinitionStart,
                germanDefinitionStart + germanDefinitionHeader.length() + definition_DE.length(), finalFlags);
    }
    if (showTransitivityInformation) {
        // Reduce the size of the transitivity information.
        ssb.setSpan(new RelativeSizeSpan(smallTextScale), transitivityStart,
                transitivityStart + transitivityHeader.length() + transitivity.length(), finalFlags);
    }
    if (!hiddenNotes.equals("")) {
        // Reduce the size of the hidden notes.
        ssb.setSpan(new RelativeSizeSpan(smallTextScale), hiddenNotesStart,
                hiddenNotesStart + hiddenNotesHeader.length() + hiddenNotes.length(), finalFlags);
    }
    Matcher m = KlingonContentProvider.Entry.ENTRY_PATTERN.matcher(expandedDefinition);
    while (m.find()) {

        // Strip the brackets {} to get the query.
        String query = expandedDefinition.substring(m.start() + 1, m.end() - 1);
        LookupClickableSpan viewLauncher = new LookupClickableSpan(query);

        // Process the linked entry information.
        KlingonContentProvider.Entry linkedEntry = new KlingonContentProvider.Entry(query, getBaseContext());
        // Log.d(TAG, "linkedEntry.getEntryName() = " + linkedEntry.getEntryName());

        // Delete the brackets and metadata parts of the string (which includes analysis components).
        ssb.delete(m.start() + 1 + linkedEntry.getEntryName().length(), m.end());
        ssb.delete(m.start(), m.start() + 1);
        int end = m.start() + linkedEntry.getEntryName().length();

        // Insert link to the category for a useful phrase.
        if (entry.isSentence() && !entry.getSentenceType().equals("")
                && linkedEntry.getEntryName().equals("*")) {
            // Delete the "*" placeholder.
            ssb.delete(m.start(), m.start() + 1);

            // Insert the category name.
            ssb.insert(m.start(), entry.getSentenceType());
            end += entry.getSentenceType().length() - 1;
        }

        // Set the font and link.
        // TODO: Source should link to description of the source.
        // This is true if this entry doesn't launch an EntryActivity.
        boolean disableEntryLink = linkedEntry.doNotLink() || linkedEntry.isSource() || linkedEntry.isURL();
        // The last span set on a range must have finalFlags.
        int maybeFinalFlags = disableEntryLink ? finalFlags : intermediateFlags;
        if (linkedEntry.isSource()) {
            // Names of sources are in italics.
            ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), m.start(), end, maybeFinalFlags);
        } else if (linkedEntry.isURL()) {
            // Linkify URL if there is one.
            String url = linkedEntry.getURL();
            if (!url.equals("")) {
                ssb.setSpan(new URLSpan(url), m.start(), end, maybeFinalFlags);
            }
        } else if (useKlingonFont) {
            // Display the text using the Klingon font. Categories (which have an entry of "*") must
            // be handled specially.
            String klingonEntryName = !linkedEntry.getEntryName().equals("*")
                    ? linkedEntry.getEntryNameInKlingonFont()
                    : KlingonContentProvider.convertStringToKlingonFont(entry.getSentenceType());
            ssb.delete(m.start(), end);
            ssb.insert(m.start(), klingonEntryName);
            end = m.start() + klingonEntryName.length();
            ssb.setSpan(new KlingonTypefaceSpan("", klingonTypeface), m.start(), end, maybeFinalFlags);
        } else {
            // Klingon is in bold serif.
            ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), m.start(), end, intermediateFlags);
            ssb.setSpan(new TypefaceSpan("serif"), m.start(), end, maybeFinalFlags);
        }
        // If linked entry is hypothetical or extended canon, insert a "?" in front.
        if (linkedEntry.isHypothetical() || linkedEntry.isExtendedCanon()) {
            ssb.insert(m.start(), "?");
            ssb.setSpan(new RelativeSizeSpan(smallTextScale), m.start(), m.start() + 1, intermediateFlags);
            ssb.setSpan(new SuperscriptSpan(), m.start(), m.start() + 1, maybeFinalFlags);
            end++;
        }
        // Only apply colours to verbs, nouns, and affixes (exclude BLUE and WHITE).
        if (!disableEntryLink) {
            // Link to view launcher.
            ssb.setSpan(viewLauncher, m.start(), end, useColours ? intermediateFlags : finalFlags);
        }
        // Set the colour last, so it's not overridden by other spans.
        if (useColours) {
            ssb.setSpan(new ForegroundColorSpan(linkedEntry.getTextColor()), m.start(), end, finalFlags);
        }
        String linkedPos = linkedEntry.getBracketedPartOfSpeech(/* isHtml */false);
        if (!linkedPos.equals("") && linkedPos.length() > 1) {
            ssb.insert(end, linkedPos);

            int rightBracketLoc = linkedPos.indexOf(")");
            if (rightBracketLoc != -1) {
                // linkedPos is always of the form " (pos)[ (def'n N)]", we want to italicise
                // the "pos" part only.
                ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), end + 2, end + rightBracketLoc,
                        finalFlags);
            }
        }

        // Rinse and repeat.
        expandedDefinition = ssb.toString();
        m = KlingonContentProvider.Entry.ENTRY_PATTERN.matcher(expandedDefinition);
    }

    // Display the entry name and definition.
    entryText.invalidate();
    entryText.setText(ssb);
    entryText.setMovementMethod(LinkMovementMethod.getInstance());
}

From source file:org.telegram.ui.Components.ChatActivityEnterView.java

public void setEditingMessageObject(MessageObject messageObject, boolean caption) {
    if (audioToSend != null || editingMessageObject == messageObject) {
        return;/*from   w  w  w  . jav a 2  s .c  om*/
    }
    if (editingMessageReqId != 0) {
        ConnectionsManager.getInstance().cancelRequest(editingMessageReqId, true);
        editingMessageReqId = 0;
    }
    editingMessageObject = messageObject;
    editingCaption = caption;
    if (editingMessageObject != null) {
        if (doneButtonAnimation != null) {
            doneButtonAnimation.cancel();
            doneButtonAnimation = null;
        }
        doneButtonContainer.setVisibility(View.VISIBLE);
        showEditDoneProgress(true, false);

        InputFilter[] inputFilters = new InputFilter[1];
        if (caption) {
            inputFilters[0] = new InputFilter.LengthFilter(200);
            if (editingMessageObject.caption != null) {
                setFieldText(Emoji.replaceEmoji(
                        new SpannableStringBuilder(editingMessageObject.caption.toString()),
                        messageEditText.getPaint().getFontMetricsInt(), AndroidUtilities.dp(20), false));
            } else {
                setFieldText("");
            }
        } else {
            inputFilters[0] = new InputFilter.LengthFilter(4096);
            if (editingMessageObject.messageText != null) {
                ArrayList<TLRPC.MessageEntity> entities = editingMessageObject.messageOwner.entities;//MessagesQuery.getEntities(message);
                MessagesQuery.sortEntities(entities);
                SpannableStringBuilder stringBuilder = new SpannableStringBuilder(
                        editingMessageObject.messageText);
                Object spansToRemove[] = stringBuilder.getSpans(0, stringBuilder.length(), Object.class);
                if (spansToRemove != null && spansToRemove.length > 0) {
                    for (int a = 0; a < spansToRemove.length; a++) {
                        stringBuilder.removeSpan(spansToRemove[a]);
                    }
                }
                if (entities != null) {
                    int addToOffset = 0;
                    try {
                        for (int a = 0; a < entities.size(); a++) {
                            TLRPC.MessageEntity entity = entities.get(a);
                            if (entity.offset + entity.length + addToOffset > stringBuilder.length()) {
                                continue;
                            }
                            if (entity instanceof TLRPC.TL_inputMessageEntityMentionName) {
                                if (entity.offset + entity.length + addToOffset < stringBuilder.length()
                                        && stringBuilder
                                                .charAt(entity.offset + entity.length + addToOffset) == ' ') {
                                    entity.length++;
                                }
                                stringBuilder.setSpan(new URLSpanUserMention(
                                        "" + ((TLRPC.TL_inputMessageEntityMentionName) entity).user_id.user_id,
                                        true), entity.offset + addToOffset,
                                        entity.offset + entity.length + addToOffset,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            } else if (entity instanceof TLRPC.TL_messageEntityCode) {
                                stringBuilder.insert(entity.offset + entity.length + addToOffset, "`");
                                stringBuilder.insert(entity.offset + addToOffset, "`");
                                addToOffset += 2;
                            } else if (entity instanceof TLRPC.TL_messageEntityPre) {
                                stringBuilder.insert(entity.offset + entity.length + addToOffset, "```");
                                stringBuilder.insert(entity.offset + addToOffset, "```");
                                addToOffset += 6;
                            } else if (entity instanceof TLRPC.TL_messageEntityBold) {
                                stringBuilder.setSpan(
                                        new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")),
                                        entity.offset + addToOffset,
                                        entity.offset + entity.length + addToOffset,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            } else if (entity instanceof TLRPC.TL_messageEntityItalic) {
                                stringBuilder.setSpan(
                                        new TypefaceSpan(AndroidUtilities.getTypeface("fonts/ritalic.ttf")),
                                        entity.offset + addToOffset,
                                        entity.offset + entity.length + addToOffset,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            }
                        }
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                setFieldText(Emoji.replaceEmoji(stringBuilder, messageEditText.getPaint().getFontMetricsInt(),
                        AndroidUtilities.dp(20), false));
            } else {
                setFieldText("");
            }
        }
        messageEditText.setFilters(inputFilters);
        openKeyboard();
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) messageEditText.getLayoutParams();
        layoutParams.rightMargin = AndroidUtilities.dp(4);
        messageEditText.setLayoutParams(layoutParams);
        sendButton.setVisibility(GONE);
        cancelBotButton.setVisibility(GONE);
        audioVideoButtonContainer.setVisibility(GONE);
        attachLayout.setVisibility(GONE);
        sendButtonContainer.setVisibility(GONE);
    } else {
        doneButtonContainer.setVisibility(View.GONE);
        messageEditText.setFilters(new InputFilter[0]);
        delegate.onMessageEditEnd(false);
        audioVideoButtonContainer.setVisibility(VISIBLE);
        attachLayout.setVisibility(VISIBLE);
        sendButtonContainer.setVisibility(VISIBLE);
        attachLayout.setScaleX(1.0f);
        attachLayout.setAlpha(1.0f);
        sendButton.setScaleX(0.1f);
        sendButton.setScaleY(0.1f);
        sendButton.setAlpha(0.0f);
        cancelBotButton.setScaleX(0.1f);
        cancelBotButton.setScaleY(0.1f);
        cancelBotButton.setAlpha(0.0f);
        audioVideoButtonContainer.setScaleX(1.0f);
        audioVideoButtonContainer.setScaleY(1.0f);
        audioVideoButtonContainer.setAlpha(1.0f);
        sendButton.setVisibility(GONE);
        cancelBotButton.setVisibility(GONE);
        messageEditText.setText("");
        if (getVisibility() == VISIBLE) {
            delegate.onAttachButtonShow();
        }
        updateFieldRight(1);
    }
    updateFieldHint();
}

From source file:kr.wdream.ui.ChatActivity.java

private void applyDraftMaybe(boolean canClear) {
    if (chatActivityEnterView == null) {
        return;// w  ww.  java  2s  .  co m
    }
    TLRPC.DraftMessage draftMessage = DraftQuery.getDraft(dialog_id);
    TLRPC.Message draftReplyMessage = draftMessage != null && draftMessage.reply_to_msg_id != 0
            ? DraftQuery.getDraftMessage(dialog_id)
            : null;
    if (chatActivityEnterView.getFieldText() == null) {
        if (draftMessage != null) {
            chatActivityEnterView.setWebPage(null, !draftMessage.no_webpage);
            CharSequence message;
            if (!draftMessage.entities.isEmpty()) {
                SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(draftMessage.message);
                MessagesQuery.sortEntities(draftMessage.entities);
                int addToOffset = 0;
                for (int a = 0; a < draftMessage.entities.size(); a++) {
                    TLRPC.MessageEntity entity = draftMessage.entities.get(a);
                    if (entity instanceof TLRPC.TL_inputMessageEntityMentionName
                            || entity instanceof TLRPC.TL_messageEntityMentionName) {
                        int user_id;
                        if (entity instanceof TLRPC.TL_inputMessageEntityMentionName) {
                            user_id = ((TLRPC.TL_inputMessageEntityMentionName) entity).user_id.user_id;
                        } else {
                            user_id = ((TLRPC.TL_messageEntityMentionName) entity).user_id;
                        }
                        if (entity.offset + addToOffset + entity.length < stringBuilder.length()
                                && stringBuilder.charAt(entity.offset + addToOffset + entity.length) == ' ') {
                            entity.length++;
                        }
                        stringBuilder.setSpan(new URLSpanUserMention("" + user_id), entity.offset + addToOffset,
                                entity.offset + addToOffset + entity.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    } else if (entity instanceof TLRPC.TL_messageEntityCode) {
                        stringBuilder.insert(entity.offset + entity.length + addToOffset, "`");
                        stringBuilder.insert(entity.offset + addToOffset, "`");
                        addToOffset += 2;
                    } else if (entity instanceof TLRPC.TL_messageEntityPre) {
                        stringBuilder.insert(entity.offset + entity.length + addToOffset, "```");
                        stringBuilder.insert(entity.offset + addToOffset, "```");
                        addToOffset += 6;
                    }
                }
                message = stringBuilder;
            } else {
                message = draftMessage.message;
            }
            chatActivityEnterView.setFieldText(message);
            if (getArguments().getBoolean("hasUrl", false)) {
                chatActivityEnterView.setSelection(draftMessage.message.indexOf('\n') + 1);
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (chatActivityEnterView != null) {
                            chatActivityEnterView.setFieldFocused(true);
                            chatActivityEnterView.openKeyboard();
                        }
                    }
                }, 700);
            }
        }
    } else if (canClear && draftMessage == null) {
        chatActivityEnterView.setFieldText("");
        showReplyPanel(false, null, null, null, false, true);
    }
    if (replyingMessageObject == null && draftReplyMessage != null) {
        replyingMessageObject = new MessageObject(draftReplyMessage,
                MessagesController.getInstance().getUsers(), false);
        showReplyPanel(true, replyingMessageObject, null, null, false, false);
    }
}