Example usage for android.text Editable removeSpan

List of usage examples for android.text Editable removeSpan

Introduction

In this page you can find the example usage for android.text Editable removeSpan.

Prototype

public void removeSpan(Object what);

Source Link

Document

Remove the specified object from the range of text to which it was attached, if any.

Usage

From source file:Main.java

/**
 * Modified from {@link android.text.Html}
 *///from  w  ww  . j a v a  2s.c o m
private static void end(Editable text, Class<?> kind, Object... replaces) {
    int len = text.length();
    Object obj = getLast(text, kind);
    int where = text.getSpanStart(obj);
    text.removeSpan(obj);
    if (where != len) {
        for (Object replace : replaces) {
            text.setSpan(replace, where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}

From source file:org.eyeseetea.malariacare.network.CustomParser.java

/** Modified from {@link android.text.Html} */
private static void end(Editable text, Class<?> kind, Object... replaces) {
    int len = text.length();
    Object obj = getLast(text, kind);
    int where = text.getSpanStart(obj);
    text.removeSpan(obj);
    if (where != len) {
        for (Object replace : replaces) {
            text.setSpan(replace, where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }/*from   w w w.j ava  2s  . c o  m*/
    }
    return;
}

From source file:org.miaowo.miaowo.util.Html.java

private static void endBlockElement(Editable text) {
    Newline n = getLast(text, Newline.class);
    if (n != null) {
        appendNewlines(text, n.mNumNewlines);
        text.removeSpan(n);
    }/*w  w w .jav a  2 s . c  o m*/

    Alignment a = getLast(text, Alignment.class);
    if (a != null) {
        setSpanFromMark(text, a, new AlignmentSpan.Standard(a.mAlignment));
    }
}

From source file:org.miaowo.miaowo.util.Html.java

private static void endFont(Editable text) {
    int len = text.length();
    Font f = getLast(text, Font.class);
    int where = text.getSpanStart(f);
    text.removeSpan(f);

    if (where != len) {
        if (!TextUtils.isEmpty(f.mColor)) {
            if (f.mColor.startsWith("@")) {
                Resources res = Resources.getSystem();
                String name = f.mColor.substring(1);
                int colorRes = res.getIdentifier(name, "color", "android");
                if (colorRes != 0) {
                    ColorStateList colors = ResourcesCompat.getColorStateList(res, colorRes, null);
                    text.setSpan(new TextAppearanceSpan(null, 0, 0, colors, null), where, len,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }//from ww  w .jav  a  2  s. c  o m
            } else {
                int c = Color.parseColor(f.mColor);
                if (c != -1) {
                    text.setSpan(new ForegroundColorSpan(c | 0xFF000000), where, len,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }

        if (f.mFace != null) {
            text.setSpan(new TypefaceSpan(f.mFace), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }
}

From source file:org.mozilla.focus.widget.InlineAutocompleteEditText.java

/**
 * Convert any autocomplete text to regular text
 *
 * @param text Current text content that may include autocomplete text
 *///  w  w w  .  jav  a2s  .co m
private boolean commitAutocomplete(final Editable text) {
    final int start = text.getSpanStart(AUTOCOMPLETE_SPAN);
    if (start < 0) {
        // No autocomplete text
        return false;
    }

    beginSettingAutocomplete();

    // Remove all spans here to convert from autocomplete text to regular text
    for (final Object span : mAutoCompleteSpans) {
        text.removeSpan(span);
    }

    // Keep mAutoCompleteResult the same because the result has not changed.
    // Reset mAutoCompletePrefixLength because the prefix now includes the autocomplete text.
    mAutoCompletePrefixLength = text.length();

    // Reshow the cursor.
    setCursorVisible(true);

    endSettingAutocomplete();

    // Filter on the new text
    if (mFilterListener != null) {
        mFilterListener.onFilter(text.toString(), null);
    }
    return true;
}

From source file:com.ruesga.rview.widget.TagEditTextView.java

private void onTagRemoveClick(final Tag tag) {
    Editable s = mTagEdit.getEditableText();
    int position = mTagList.indexOf(tag);
    mLockEdit = true;/*  ww w.  j av  a 2  s.  c o m*/
    mTagList.remove(position);
    ImageSpan[] spans = s.getSpans(position, position + 1, ImageSpan.class);
    for (ImageSpan span : spans) {
        s.removeSpan(span);
    }
    s.delete(position, position + 1);
    mLockEdit = false;

    notifyTagRemoved(tag);
}

From source file:com.taobao.weex.dom.WXTextDomObject.java

/**
 * Truncate the source span to the specified lines.
 * Caller of this method must ensure that the lines of text is <strong>greater than desired lines and need truncate</strong>.
 * Otherwise, unexpected behavior may happen.
 * @param source The source span./* w ww.  j a  va 2 s . c om*/
 * @param paint the textPaint
 * @param desired specified lines.
 * @param truncateAt truncate method, null value means clipping overflow text directly, non-null value means using ellipsis strategy to clip
 * @return The spans after clipped.
 */
private @NonNull Spanned truncate(@Nullable Editable source, @NonNull TextPaint paint, int desired,
        @Nullable TextUtils.TruncateAt truncateAt) {
    Spanned ret = new SpannedString("");
    if (!TextUtils.isEmpty(source) && source.length() > 0) {
        if (truncateAt != null) {
            source.append(ELLIPSIS);
            Object[] spans = source.getSpans(0, source.length(), Object.class);
            for (Object span : spans) {
                int start = source.getSpanStart(span);
                int end = source.getSpanEnd(span);
                if (start == 0 && end == source.length() - 1) {
                    source.removeSpan(span);
                    source.setSpan(span, 0, source.length(), source.getSpanFlags(span));
                }
            }
        }

        StaticLayout layout;
        int startOffset;

        while (source.length() > 1) {
            startOffset = source.length() - 1;
            if (truncateAt != null) {
                startOffset -= 1;
            }
            source.delete(startOffset, startOffset + 1);
            layout = new StaticLayout(source, paint, desired, Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
            if (layout.getLineCount() <= 1) {
                ret = source;
                break;
            }
        }
    }
    return ret;
}

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

/**
 * Remove selection from this chip. Unselecting a RecipientChip will render the chip without a delete icon and with
 * an unfocused background. This is called when the RecipientChip no longer has focus.
 *///  w  ww.  jav a 2 s  . c o m
private void unselectChip(final DrawableRecipientChip chip) {
    final int start = getChipStart(chip);
    final int end = getChipEnd(chip);
    final Editable editable = getText();
    mSelectedChip = null;
    if (start == -1 || end == -1) {
        Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
        setSelection(editable.length());
        commitDefault();
    } else {
        getSpannable().removeSpan(chip);
        QwertyKeyListener.markAsReplaced(editable, start, end, "");
        editable.removeSpan(chip);
        try {
            if (!mNoChips)
                editable.setSpan(constructChipSpan(chip.getEntry(), false, false), start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (final NullPointerException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }
    setCursorVisible(true);
    setSelection(editable.length());
    /*if(mAlternatesPopup!=null&&mAlternatesPopup.isShowing())
      mAlternatesPopup.dismiss();*/
}

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

public ChatActivityEnterView(Activity context, SizeNotifierFrameLayout parent, ChatActivity fragment,
        final boolean isChat) {
    super(context);

    dotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    dotPaint.setColor(Theme.getColor(Theme.key_chat_emojiPanelNewTrending));
    setFocusable(true);//from  w  w  w .j  a v  a2s .  c  o  m
    setFocusableInTouchMode(true);
    setWillNotDraw(false);

    NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStarted);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStartError);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordStopped);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.recordProgressChanged);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeChats);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidSent);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioRouteChanged);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidReset);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged);
    NotificationCenter.getInstance().addObserver(this, NotificationCenter.featuredStickersDidLoaded);
    parentActivity = context;
    parentFragment = fragment;
    sizeNotifierLayout = parent;
    sizeNotifierLayout.setDelegate(this);
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig",
            Activity.MODE_PRIVATE);
    sendByEnter = preferences.getBoolean("send_by_enter", false);

    textFieldContainer = new LinearLayout(context);
    textFieldContainer.setOrientation(LinearLayout.HORIZONTAL);
    addView(textFieldContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT,
            Gravity.LEFT | Gravity.TOP, 0, 2, 0, 0));

    FrameLayout frameLayout = new FrameLayout(context);
    textFieldContainer.addView(frameLayout, LayoutHelper.createLinear(0, LayoutHelper.WRAP_CONTENT, 1.0f));

    emojiButton = new ImageView(context) {
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            if (attachLayout != null && (emojiView == null || emojiView.getVisibility() != VISIBLE)
                    && !StickersQuery.getUnreadStickerSets().isEmpty() && dotPaint != null) {
                int x = canvas.getWidth() / 2 + AndroidUtilities.dp(4 + 5);
                int y = canvas.getHeight() / 2 - AndroidUtilities.dp(13 - 5);
                canvas.drawCircle(x, y, AndroidUtilities.dp(5), dotPaint);
            }
        }
    };
    emojiButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons),
            PorterDuff.Mode.MULTIPLY));
    emojiButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    emojiButton.setPadding(0, AndroidUtilities.dp(1), 0, 0);
    //        if (Build.VERSION.SDK_INT >= 21) {
    //            emojiButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
    //        }
    setEmojiButtonImage();
    frameLayout.addView(emojiButton,
            LayoutHelper.createFrame(48, 48, Gravity.BOTTOM | Gravity.LEFT, 3, 0, 0, 0));
    emojiButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!isPopupShowing() || currentPopupContentType != 0) {
                showPopup(1, 0);
                emojiView.onOpen(messageEditText.length() > 0
                        && !messageEditText.getText().toString().startsWith("@gif"));
            } else {
                openKeyboardInternal();
                removeGifFromInputField();
            }
        }
    });

    messageEditText = new EditTextCaption(context) {
        @Override
        public InputConnection onCreateInputConnection(EditorInfo editorInfo) {
            final InputConnection ic = super.onCreateInputConnection(editorInfo);
            EditorInfoCompat.setContentMimeTypes(editorInfo,
                    new String[] { "image/gif", "image/*", "image/jpg", "image/png" });

            final InputConnectionCompat.OnCommitContentListener callback = new InputConnectionCompat.OnCommitContentListener() {
                @Override
                public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags,
                        Bundle opts) {
                    if (BuildCompat.isAtLeastNMR1()
                            && (flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
                        try {
                            inputContentInfo.requestPermission();
                        } catch (Exception e) {
                            return false;
                        }
                    }
                    ClipDescription description = inputContentInfo.getDescription();
                    if (description.hasMimeType("image/gif")) {
                        SendMessagesHelper.prepareSendingDocument(null, null, inputContentInfo.getContentUri(),
                                "image/gif", dialog_id, replyingMessageObject, inputContentInfo);
                    } else {
                        SendMessagesHelper.prepareSendingPhoto(null, inputContentInfo.getContentUri(),
                                dialog_id, replyingMessageObject, null, null, inputContentInfo);
                    }
                    if (delegate != null) {
                        delegate.onMessageSend(null);
                    }
                    return true;
                }
            };
            return InputConnectionCompat.createWrapper(ic, editorInfo, callback);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (isPopupShowing() && event.getAction() == MotionEvent.ACTION_DOWN) {
                showPopup(AndroidUtilities.usingHardwareInput ? 0 : 2, 0);
                openKeyboardInternal();
            }
            try {
                return super.onTouchEvent(event);
            } catch (Exception e) {
                FileLog.e(e);
            }
            return false;
        }
    };
    updateFieldHint();
    messageEditText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    messageEditText.setInputType(messageEditText.getInputType() | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES
            | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
    messageEditText.setSingleLine(false);
    messageEditText.setMaxLines(4);
    messageEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    messageEditText.setGravity(Gravity.BOTTOM);
    messageEditText.setPadding(0, AndroidUtilities.dp(11), 0, AndroidUtilities.dp(12));
    messageEditText.setBackgroundDrawable(null);
    messageEditText.setTextColor(Theme.getColor(Theme.key_chat_messagePanelText));
    messageEditText.setHintColor(Theme.getColor(Theme.key_chat_messagePanelHint));
    messageEditText.setHintTextColor(Theme.getColor(Theme.key_chat_messagePanelHint));
    frameLayout.addView(messageEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM, 52, 0, isChat ? 50 : 2, 0));
    messageEditText.setOnKeyListener(new OnKeyListener() {

        boolean ctrlPressed = false;

        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if (i == KeyEvent.KEYCODE_BACK && !keyboardVisible && isPopupShowing()) {
                if (keyEvent.getAction() == 1) {
                    if (currentPopupContentType == 1 && botButtonsMessageObject != null) {
                        SharedPreferences preferences = ApplicationLoader.applicationContext
                                .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                        preferences.edit().putInt("hidekeyboard_" + dialog_id, botButtonsMessageObject.getId())
                                .commit();
                    }
                    showPopup(0, 0);
                    removeGifFromInputField();
                }
                return true;
            } else if (i == KeyEvent.KEYCODE_ENTER && (ctrlPressed || sendByEnter)
                    && keyEvent.getAction() == KeyEvent.ACTION_DOWN && editingMessageObject == null) {
                sendMessage();
                return true;
            } else if (i == KeyEvent.KEYCODE_CTRL_LEFT || i == KeyEvent.KEYCODE_CTRL_RIGHT) {
                ctrlPressed = keyEvent.getAction() == KeyEvent.ACTION_DOWN;
                return true;
            }
            return false;
        }
    });
    messageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        boolean ctrlPressed = false;

        @Override
        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
            if (i == EditorInfo.IME_ACTION_SEND) {
                sendMessage();
                return true;
            } else if (keyEvent != null && i == EditorInfo.IME_NULL) {
                if ((ctrlPressed || sendByEnter) && keyEvent.getAction() == KeyEvent.ACTION_DOWN
                        && editingMessageObject == null) {
                    sendMessage();
                    return true;
                } else if (i == KeyEvent.KEYCODE_CTRL_LEFT || i == KeyEvent.KEYCODE_CTRL_RIGHT) {
                    ctrlPressed = keyEvent.getAction() == KeyEvent.ACTION_DOWN;
                    return true;
                }
            }
            return false;
        }
    });
    messageEditText.addTextChangedListener(new TextWatcher() {
        boolean processChange = false;

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            if (innerTextChange == 1) {
                return;
            }
            checkSendButton(true);
            CharSequence message = AndroidUtilities.getTrimmedString(charSequence.toString());
            if (delegate != null) {
                if (!ignoreTextChange) {
                    if (count > 2 || charSequence == null || charSequence.length() == 0) {
                        messageWebPageSearch = true;
                    }
                    delegate.onTextChanged(charSequence, before > count + 1 || (count - before) > 2);
                }
            }
            if (innerTextChange != 2 && before != count && (count - before) > 1) {
                processChange = true;
            }
            if (editingMessageObject == null && !canWriteToChannel && message.length() != 0
                    && lastTypingTimeSend < System.currentTimeMillis() - 5000 && !ignoreTextChange) {
                int currentTime = ConnectionsManager.getInstance().getCurrentTime();
                TLRPC.User currentUser = null;
                if ((int) dialog_id > 0) {
                    currentUser = MessagesController.getInstance().getUser((int) dialog_id);
                }
                if (currentUser != null && (currentUser.id == UserConfig.getClientUserId()
                        || currentUser.status != null && currentUser.status.expires < currentTime
                                && !MessagesController.getInstance().onlinePrivacy
                                        .containsKey(currentUser.id))) {
                    return;
                }
                lastTypingTimeSend = System.currentTimeMillis();
                if (delegate != null) {
                    delegate.needSendTyping();
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (innerTextChange != 0) {
                return;
            }
            if (sendByEnter && editable.length() > 0 && editable.charAt(editable.length() - 1) == '\n'
                    && editingMessageObject == null) {
                sendMessage();
            }
            if (processChange) {
                ImageSpan[] spans = editable.getSpans(0, editable.length(), ImageSpan.class);
                for (int i = 0; i < spans.length; i++) {
                    editable.removeSpan(spans[i]);
                }
                Emoji.replaceEmoji(editable, messageEditText.getPaint().getFontMetricsInt(),
                        AndroidUtilities.dp(20), false);
                processChange = false;
            }
        }
    });

    if (isChat) {
        attachLayout = new LinearLayout(context);
        attachLayout.setOrientation(LinearLayout.HORIZONTAL);
        attachLayout.setEnabled(false);
        attachLayout.setPivotX(AndroidUtilities.dp(48));
        frameLayout.addView(attachLayout,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 48, Gravity.BOTTOM | Gravity.RIGHT));

        botButton = new ImageView(context);
        botButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons),
                PorterDuff.Mode.MULTIPLY));
        botButton.setImageResource(R.drawable.bot_keyboard2);
        botButton.setScaleType(ImageView.ScaleType.CENTER);
        botButton.setVisibility(GONE);
        //            if (Build.VERSION.SDK_INT >= 21) {
        //                botButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
        //            }
        attachLayout.addView(botButton, LayoutHelper.createLinear(48, 48));
        botButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (botReplyMarkup != null) {
                    if (!isPopupShowing() || currentPopupContentType != 1) {
                        showPopup(1, 1);
                        SharedPreferences preferences = ApplicationLoader.applicationContext
                                .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                        preferences.edit().remove("hidekeyboard_" + dialog_id).commit();
                    } else {
                        if (currentPopupContentType == 1 && botButtonsMessageObject != null) {
                            SharedPreferences preferences = ApplicationLoader.applicationContext
                                    .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                            preferences.edit()
                                    .putInt("hidekeyboard_" + dialog_id, botButtonsMessageObject.getId())
                                    .commit();
                        }
                        openKeyboardInternal();
                    }
                } else if (hasBotCommands) {
                    setFieldText("/");
                    messageEditText.requestFocus();
                    openKeyboard();
                }
            }
        });

        notifyButton = new ImageView(context);
        notifyButton.setImageResource(silent ? R.drawable.notify_members_off : R.drawable.notify_members_on);
        notifyButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons),
                PorterDuff.Mode.MULTIPLY));
        notifyButton.setScaleType(ImageView.ScaleType.CENTER);
        notifyButton.setVisibility(canWriteToChannel ? VISIBLE : GONE);
        //            if (Build.VERSION.SDK_INT >= 21) {
        //                notifyButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
        //            }
        attachLayout.addView(notifyButton, LayoutHelper.createLinear(48, 48));
        notifyButton.setOnClickListener(new OnClickListener() {

            private Toast visibleToast;

            @Override
            public void onClick(View v) {
                silent = !silent;
                notifyButton.setImageResource(
                        silent ? R.drawable.notify_members_off : R.drawable.notify_members_on);
                ApplicationLoader.applicationContext
                        .getSharedPreferences("Notifications", Activity.MODE_PRIVATE).edit()
                        .putBoolean("silent_" + dialog_id, silent).commit();
                NotificationsController.updateServerNotificationsSettings(dialog_id);
                try {
                    if (visibleToast != null) {
                        visibleToast.cancel();
                    }
                } catch (Exception e) {
                    FileLog.e(e);
                }
                if (silent) {
                    visibleToast = Toast.makeText(parentActivity, LocaleController
                            .getString("ChannelNotifyMembersInfoOff", R.string.ChannelNotifyMembersInfoOff),
                            Toast.LENGTH_SHORT);
                } else {
                    visibleToast = Toast.makeText(parentActivity, LocaleController
                            .getString("ChannelNotifyMembersInfoOn", R.string.ChannelNotifyMembersInfoOn),
                            Toast.LENGTH_SHORT);
                }
                visibleToast.show();
                updateFieldHint();
            }
        });

        attachButton = new ImageView(context);
        attachButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons),
                PorterDuff.Mode.MULTIPLY));
        attachButton.setImageResource(R.drawable.ic_ab_attach);
        attachButton.setScaleType(ImageView.ScaleType.CENTER);
        //            if (Build.VERSION.SDK_INT >= 21) {
        //                attachButton.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
        //            }
        attachLayout.addView(attachButton, LayoutHelper.createLinear(48, 48));
        attachButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                delegate.didPressedAttachButton();
            }
        });
    }

    recordedAudioPanel = new FrameLayout(context);
    recordedAudioPanel.setVisibility(audioToSend == null ? GONE : VISIBLE);
    recordedAudioPanel.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground));
    recordedAudioPanel.setFocusable(true);
    recordedAudioPanel.setFocusableInTouchMode(true);
    recordedAudioPanel.setClickable(true);
    frameLayout.addView(recordedAudioPanel,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM));

    recordDeleteImageView = new ImageView(context);
    recordDeleteImageView.setScaleType(ImageView.ScaleType.CENTER);
    recordDeleteImageView.setImageResource(R.drawable.ic_ab_delete);
    recordDeleteImageView.setColorFilter(new PorterDuffColorFilter(
            Theme.getColor(Theme.key_chat_messagePanelVoiceDelete), PorterDuff.Mode.MULTIPLY));
    recordedAudioPanel.addView(recordDeleteImageView, LayoutHelper.createFrame(48, 48));
    recordDeleteImageView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            MessageObject playing = MediaController.getInstance().getPlayingMessageObject();
            if (playing != null && playing == audioToSendMessageObject) {
                MediaController.getInstance().cleanupPlayer(true, true);
            }
            if (audioToSendPath != null) {
                new File(audioToSendPath).delete();
            }
            hideRecordedAudioPanel();
            checkSendButton(true);
        }
    });

    recordedAudioBackground = new View(context);
    recordedAudioBackground.setBackgroundDrawable(Theme.createRoundRectDrawable(AndroidUtilities.dp(16),
            Theme.getColor(Theme.key_chat_recordedVoiceBackground)));
    recordedAudioPanel.addView(recordedAudioBackground, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 32,
            Gravity.CENTER_VERTICAL | Gravity.LEFT, 48, 0, 0, 0));

    recordedAudioSeekBar = new SeekBarWaveformView(context);
    recordedAudioPanel.addView(recordedAudioSeekBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 32,
            Gravity.CENTER_VERTICAL | Gravity.LEFT, 48 + 44, 0, 52, 0));

    playDrawable = Theme.createSimpleSelectorDrawable(context, R.drawable.s_play,
            Theme.getColor(Theme.key_chat_recordedVoicePlayPause),
            Theme.getColor(Theme.key_chat_recordedVoicePlayPausePressed));
    pauseDrawable = Theme.createSimpleSelectorDrawable(context, R.drawable.s_pause,
            Theme.getColor(Theme.key_chat_recordedVoicePlayPause),
            Theme.getColor(Theme.key_chat_recordedVoicePlayPausePressed));

    recordedAudioPlayButton = new ImageView(context);
    recordedAudioPlayButton.setImageDrawable(playDrawable);
    recordedAudioPlayButton.setScaleType(ImageView.ScaleType.CENTER);
    recordedAudioPanel.addView(recordedAudioPlayButton,
            LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.BOTTOM, 48, 0, 0, 0));
    recordedAudioPlayButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (audioToSend == null) {
                return;
            }
            if (MediaController.getInstance().isPlayingAudio(audioToSendMessageObject)
                    && !MediaController.getInstance().isAudioPaused()) {
                MediaController.getInstance().pauseAudio(audioToSendMessageObject);
                recordedAudioPlayButton.setImageDrawable(playDrawable);
            } else {
                recordedAudioPlayButton.setImageDrawable(pauseDrawable);
                MediaController.getInstance().playAudio(audioToSendMessageObject);
            }
        }
    });

    recordedAudioTimeTextView = new TextView(context);
    recordedAudioTimeTextView.setTextColor(Theme.getColor(Theme.key_chat_messagePanelVoiceDuration));
    recordedAudioTimeTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    recordedAudioPanel.addView(recordedAudioTimeTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0, 13, 0));

    recordPanel = new FrameLayout(context);
    recordPanel.setVisibility(GONE);
    recordPanel.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground));
    frameLayout.addView(recordPanel, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM));

    slideText = new LinearLayout(context);
    slideText.setOrientation(LinearLayout.HORIZONTAL);
    recordPanel.addView(slideText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 30, 0, 0, 0));

    recordCancelImage = new ImageView(context);
    recordCancelImage.setImageResource(R.drawable.slidearrow);
    recordCancelImage.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_recordVoiceCancel),
            PorterDuff.Mode.MULTIPLY));
    slideText.addView(recordCancelImage, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 0, 1, 0, 0));

    recordCancelText = new TextView(context);
    recordCancelText.setText(LocaleController.getString("SlideToCancel", R.string.SlideToCancel));
    recordCancelText.setTextColor(Theme.getColor(Theme.key_chat_recordVoiceCancel));
    recordCancelText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
    slideText.addView(recordCancelText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 6, 0, 0, 0));

    recordTimeContainer = new LinearLayout(context);
    recordTimeContainer.setOrientation(LinearLayout.HORIZONTAL);
    recordTimeContainer.setPadding(AndroidUtilities.dp(13), 0, 0, 0);
    recordTimeContainer.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground));
    recordPanel.addView(recordTimeContainer, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL));

    recordDot = new RecordDot(context);
    recordTimeContainer.addView(recordDot,
            LayoutHelper.createLinear(11, 11, Gravity.CENTER_VERTICAL, 0, 1, 0, 0));

    recordTimeText = new TextView(context);
    recordTimeText.setText("00:00");
    recordTimeText.setTextColor(Theme.getColor(Theme.key_chat_recordTime));
    recordTimeText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    recordTimeContainer.addView(recordTimeText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 6, 0, 0, 0));

    sendButtonContainer = new FrameLayout(context);
    textFieldContainer.addView(sendButtonContainer, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM));

    audioVideoButtonContainer = new FrameLayout(context);
    audioVideoButtonContainer.setBackgroundColor(Theme.getColor(Theme.key_chat_messagePanelBackground));
    audioVideoButtonContainer.setSoundEffectsEnabled(false);
    sendButtonContainer.addView(audioVideoButtonContainer, LayoutHelper.createFrame(48, 48));
    audioVideoButtonContainer.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                if (hasRecordVideo) {
                    recordAudioVideoRunnableStarted = true;
                    AndroidUtilities.runOnUIThread(recordAudioVideoRunnable, 150);
                } else {
                    recordAudioVideoRunnable.run();
                }
            } else if (motionEvent.getAction() == MotionEvent.ACTION_UP
                    || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
                if (recordAudioVideoRunnableStarted) {
                    AndroidUtilities.cancelRunOnUIThread(recordAudioVideoRunnable);
                    setRecordVideoButtonVisible(videoSendButton.getTag() == null, true);
                } else {
                    startedDraggingX = -1;
                    if (hasRecordVideo && videoSendButton.getTag() != null) {
                        delegate.needStartRecordVideo(1);
                    } else {
                        MediaController.getInstance().stopRecording(1);
                    }
                    recordingAudioVideo = false;
                    updateRecordIntefrace();
                }
            } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && recordingAudioVideo) {
                float x = motionEvent.getX();
                if (x < -distCanMove) {
                    if (hasRecordVideo && videoSendButton.getTag() != null) {
                        delegate.needStartRecordVideo(2);
                    } else {
                        MediaController.getInstance().stopRecording(0);
                    }
                    recordingAudioVideo = false;
                    updateRecordIntefrace();
                }

                x = x + audioVideoButtonContainer.getX();
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) slideText.getLayoutParams();
                if (startedDraggingX != -1) {
                    float dist = (x - startedDraggingX);
                    recordCircle.setTranslationX(dist);
                    params.leftMargin = AndroidUtilities.dp(30) + (int) dist;
                    slideText.setLayoutParams(params);
                    float alpha = 1.0f + dist / distCanMove;
                    if (alpha > 1) {
                        alpha = 1;
                    } else if (alpha < 0) {
                        alpha = 0;
                    }
                    slideText.setAlpha(alpha);
                }
                if (x <= slideText.getX() + slideText.getWidth() + AndroidUtilities.dp(30)) {
                    if (startedDraggingX == -1) {
                        startedDraggingX = x;
                        distCanMove = (recordPanel.getMeasuredWidth() - slideText.getMeasuredWidth()
                                - AndroidUtilities.dp(48)) / 2.0f;
                        if (distCanMove <= 0) {
                            distCanMove = AndroidUtilities.dp(80);
                        } else if (distCanMove > AndroidUtilities.dp(80)) {
                            distCanMove = AndroidUtilities.dp(80);
                        }
                    }
                }
                if (params.leftMargin > AndroidUtilities.dp(30)) {
                    params.leftMargin = AndroidUtilities.dp(30);
                    recordCircle.setTranslationX(0);
                    slideText.setLayoutParams(params);
                    slideText.setAlpha(1);
                    startedDraggingX = -1;
                }
            }
            view.onTouchEvent(motionEvent);
            return true;
        }
    });

    audioSendButton = new ImageView(context);
    audioSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    audioSendButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelIcons),
            PorterDuff.Mode.MULTIPLY));
    audioSendButton.setImageResource(R.drawable.mic);
    audioSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0);
    audioVideoButtonContainer.addView(audioSendButton, LayoutHelper.createFrame(48, 48));

    if (hasRecordVideo) {
        videoSendButton = new ImageView(context);
        videoSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        videoSendButton.setColorFilter(new PorterDuffColorFilter(
                Theme.getColor(Theme.key_chat_messagePanelIcons), PorterDuff.Mode.MULTIPLY));
        videoSendButton.setImageResource(R.drawable.ic_msg_panel_video);
        videoSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0);
        audioVideoButtonContainer.addView(videoSendButton, LayoutHelper.createFrame(48, 48));
    }

    recordCircle = new RecordCircle(context);
    recordCircle.setVisibility(GONE);
    sizeNotifierLayout.addView(recordCircle,
            LayoutHelper.createFrame(124, 124, Gravity.BOTTOM | Gravity.RIGHT, 0, 0, -36, -38));

    cancelBotButton = new ImageView(context);
    cancelBotButton.setVisibility(INVISIBLE);
    cancelBotButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    cancelBotButton.setImageDrawable(progressDrawable = new CloseProgressDrawable2());
    progressDrawable.setColorFilter(new PorterDuffColorFilter(
            Theme.getColor(Theme.key_chat_messagePanelCancelInlineBot), PorterDuff.Mode.MULTIPLY));
    cancelBotButton.setSoundEffectsEnabled(false);
    cancelBotButton.setScaleX(0.1f);
    cancelBotButton.setScaleY(0.1f);
    cancelBotButton.setAlpha(0.0f);
    sendButtonContainer.addView(cancelBotButton, LayoutHelper.createFrame(48, 48));
    cancelBotButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            String text = messageEditText.getText().toString();
            int idx = text.indexOf(' ');
            if (idx == -1 || idx == text.length() - 1) {
                setFieldText("");
            } else {
                setFieldText(text.substring(0, idx + 1));
            }
        }
    });

    sendButton = new ImageView(context);
    sendButton.setVisibility(INVISIBLE);
    sendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    sendButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_messagePanelSend),
            PorterDuff.Mode.MULTIPLY));
    sendButton.setImageResource(R.drawable.ic_send);
    sendButton.setSoundEffectsEnabled(false);
    sendButton.setScaleX(0.1f);
    sendButton.setScaleY(0.1f);
    sendButton.setAlpha(0.0f);
    sendButtonContainer.addView(sendButton, LayoutHelper.createFrame(48, 48));
    sendButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            sendMessage();
        }
    });

    doneButtonContainer = new FrameLayout(context);
    doneButtonContainer.setVisibility(GONE);
    textFieldContainer.addView(doneButtonContainer, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM));
    //        if (Build.VERSION.SDK_INT >= 21) {
    //            doneButtonContainer.setBackgroundDrawable(Theme.createSelectorDrawable(Theme.INPUT_FIELD_SELECTOR_COLOR));
    //        }
    doneButtonContainer.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            doneEditingMessage();
        }
    });

    doneButtonImage = new ImageView(context);
    doneButtonImage.setScaleType(ImageView.ScaleType.CENTER);
    doneButtonImage.setImageResource(R.drawable.edit_done);
    doneButtonImage.setColorFilter(
            new PorterDuffColorFilter(Theme.getColor(Theme.key_chat_editDoneIcon), PorterDuff.Mode.MULTIPLY));
    doneButtonContainer.addView(doneButtonImage, LayoutHelper.createFrame(48, 48));

    doneButtonProgress = new ContextProgressView(context, 0);
    doneButtonProgress.setVisibility(View.INVISIBLE);
    doneButtonContainer.addView(doneButtonProgress,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    SharedPreferences sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("emoji",
            Context.MODE_PRIVATE);
    keyboardHeight = sharedPreferences.getInt("kbd_height", AndroidUtilities.dp(200));
    keyboardHeightLand = sharedPreferences.getInt("kbd_height_land3", AndroidUtilities.dp(200));

    setRecordVideoButtonVisible(false, false);
    checkSendButton(false);
}

From source file:org.telegram.ui.ChatActivity.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (fragmentView == null) {
        fragmentView = inflater.inflate(R.layout.chat_layout, container, false);

        sizeNotifierRelativeLayout = (SizeNotifierRelativeLayout) fragmentView.findViewById(R.id.chat_layout);
        sizeNotifierRelativeLayout.delegate = this;
        contentView = sizeNotifierRelativeLayout;

        emptyView = (TextView) fragmentView.findViewById(R.id.searchEmptyView);
        chatListView = (LayoutListView) fragmentView.findViewById(R.id.chat_list_view);
        chatListView.setAdapter(chatAdapter = new ChatAdapter(parentActivity));
        topPanel = fragmentView.findViewById(R.id.top_panel);
        topPlaneClose = (ImageView) fragmentView.findViewById(R.id.top_plane_close);
        topPanelText = (TextView) fragmentView.findViewById(R.id.top_panel_text);
        bottomOverlay = fragmentView.findViewById(R.id.bottom_overlay);
        bottomOverlayText = (TextView) fragmentView.findViewById(R.id.bottom_overlay_text);
        View bottomOverlayChat = fragmentView.findViewById(R.id.bottom_overlay_chat);
        progressView = fragmentView.findViewById(R.id.progressLayout);
        pagedownButton = fragmentView.findViewById(R.id.pagedown_button);
        audioSendButton = (ImageButton) fragmentView.findViewById(R.id.chat_audio_send_button);
        View progressViewInner = progressView.findViewById(R.id.progressLayoutInner);

        updateContactStatus();/*w  w w .  j  a va 2 s  .c  o  m*/

        ImageView backgroundImage = (ImageView) fragmentView.findViewById(R.id.background_image);

        SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig",
                Activity.MODE_PRIVATE);
        int selectedBackground = preferences.getInt("selectedBackground", 1000001);
        int selectedColor = preferences.getInt("selectedColor", 0);
        if (selectedColor != 0) {
            backgroundImage.setBackgroundColor(selectedColor);
            chatListView.setCacheColorHint(selectedColor);
        } else {
            chatListView.setCacheColorHint(0);
            if (selectedBackground == 1000001) {
                backgroundImage.setImageResource(R.drawable.background_hd);
            } else {
                File toFile = new File(ApplicationLoader.applicationContext.getFilesDir(), "wallpaper.jpg");
                if (toFile.exists()) {
                    if (ApplicationLoader.cachedWallpaper != null) {
                        backgroundImage.setImageBitmap(ApplicationLoader.cachedWallpaper);
                    } else {
                        backgroundImage.setImageURI(Uri.fromFile(toFile));
                        if (backgroundImage.getDrawable() instanceof BitmapDrawable) {
                            ApplicationLoader.cachedWallpaper = ((BitmapDrawable) backgroundImage.getDrawable())
                                    .getBitmap();
                        }
                    }
                    isCustomTheme = true;
                } else {
                    backgroundImage.setImageResource(R.drawable.background_hd);
                }
            }
        }

        if (currentEncryptedChat != null) {
            secretChatPlaceholder = contentView.findViewById(R.id.secret_placeholder);
            if (isCustomTheme) {
                secretChatPlaceholder.setBackgroundResource(R.drawable.system_black);
            } else {
                secretChatPlaceholder.setBackgroundResource(R.drawable.system_blue);
            }
            secretViewStatusTextView = (TextView) contentView.findViewById(R.id.invite_text);
            secretChatPlaceholder.setPadding(Utilities.dp(16), Utilities.dp(12), Utilities.dp(16),
                    Utilities.dp(12));

            View v = contentView.findViewById(R.id.secret_placeholder);
            v.setVisibility(View.VISIBLE);

            if (currentEncryptedChat.admin_id == UserConfig.clientUserId) {
                if (currentUser.first_name.length() > 0) {
                    secretViewStatusTextView
                            .setText(String.format(getStringEntry(R.string.EncryptedPlaceholderTitleOutgoing),
                                    currentUser.first_name));
                } else {
                    secretViewStatusTextView.setText(String.format(
                            getStringEntry(R.string.EncryptedPlaceholderTitleOutgoing), currentUser.last_name));
                }
            } else {
                if (currentUser.first_name.length() > 0) {
                    secretViewStatusTextView
                            .setText(String.format(getStringEntry(R.string.EncryptedPlaceholderTitleIncoming),
                                    currentUser.first_name));
                } else {
                    secretViewStatusTextView.setText(String.format(
                            getStringEntry(R.string.EncryptedPlaceholderTitleIncoming), currentUser.last_name));
                }
            }

            updateSecretStatus();
        }

        if (isCustomTheme) {
            progressViewInner.setBackgroundResource(R.drawable.system_loader2);
            emptyView.setBackgroundResource(R.drawable.system_black);
        } else {
            progressViewInner.setBackgroundResource(R.drawable.system_loader1);
            emptyView.setBackgroundResource(R.drawable.system_blue);
        }
        emptyView.setPadding(Utilities.dp(7), Utilities.dp(1), Utilities.dp(7), Utilities.dp(1));

        if (currentUser != null && currentUser.id == 333000) {
            emptyView.setText(R.string.GotAQuestion);
        }

        chatListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long id) {
                if (mActionMode == null) {
                    createMenu(view, false);
                }
                return true;
            }
        });

        chatListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                if (visibleItemCount > 0) {
                    if (firstVisibleItem <= 4) {
                        if (!endReached && !loading) {
                            if (messagesByDays.size() != 0) {
                                MessagesController.Instance.loadMessages(dialog_id, 0, 20, maxMessageId,
                                        !cacheEndReaced, minDate, classGuid, false, false);
                            } else {
                                MessagesController.Instance.loadMessages(dialog_id, 0, 20, 0, !cacheEndReaced,
                                        minDate, classGuid, false, false);
                            }
                            loading = true;
                        }
                    }
                    if (firstVisibleItem + visibleItemCount >= totalItemCount - 6) {
                        if (!unread_end_reached && !loadingForward) {
                            MessagesController.Instance.loadMessages(dialog_id, 0, 20, minMessageId, true,
                                    maxDate, classGuid, false, true);
                            loadingForward = true;
                        }
                    }
                    if (firstVisibleItem + visibleItemCount == totalItemCount && unread_end_reached) {
                        showPagedownButton(false, true);
                    }
                } else {
                    showPagedownButton(false, false);
                }
            }
        });

        messsageEditText = (EditText) fragmentView.findViewById(R.id.chat_text_edit);

        sendButton = (ImageButton) fragmentView.findViewById(R.id.chat_send_button);
        sendButton.setEnabled(false);
        sendButton.setVisibility(View.INVISIBLE);
        emojiButton = (ImageView) fragmentView.findViewById(R.id.chat_smile_button);

        if (loading && messages.isEmpty()) {
            progressView.setVisibility(View.VISIBLE);
            chatListView.setEmptyView(null);
        } else {
            progressView.setVisibility(View.GONE);
            if (currentEncryptedChat == null) {
                chatListView.setEmptyView(emptyView);
            } else {
                chatListView.setEmptyView(secretChatPlaceholder);
            }
        }

        emojiButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (emojiPopup == null) {
                    showEmojiPopup(true);
                } else {
                    showEmojiPopup(!emojiPopup.isShowing());
                }
            }
        });

        messsageEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == 4 && !keyboardVisible && emojiPopup != null && emojiPopup.isShowing()) {
                    if (keyEvent.getAction() == 1) {
                        showEmojiPopup(false);
                    }
                    return true;
                } else if (i == KeyEvent.KEYCODE_ENTER && sendByEnter
                        && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    sendMessage();
                    return true;
                }
                return false;
            }
        });

        messsageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEND) {
                    sendMessage();
                    return true;
                } else if (sendByEnter) {
                    if (keyEvent != null && i == EditorInfo.IME_NULL
                            && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                        sendMessage();
                        return true;
                    }
                }
                return false;
            }
        });

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendMessage();
            }
        });

        audioSendButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    startRecording();
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    stopRecording();
                }
                return false;
            }
        });

        pagedownButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (unread_end_reached || first_unread_id == 0) {
                    chatListView.setSelectionFromTop(messages.size() - 1,
                            -10000 - chatListView.getPaddingTop());
                } else {
                    messages.clear();
                    messagesByDays.clear();
                    messagesDict.clear();
                    progressView.setVisibility(View.VISIBLE);
                    chatListView.setEmptyView(null);
                    maxMessageId = Integer.MAX_VALUE;
                    minMessageId = Integer.MIN_VALUE;
                    maxDate = Integer.MIN_VALUE;
                    minDate = 0;
                    MessagesController.Instance.loadMessages(dialog_id, 0, 30, 0, true, 0, classGuid, true,
                            false);
                    loading = true;
                    chatAdapter.notifyDataSetChanged();
                }
            }
        });

        checkSendButton();

        messsageEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                String message = charSequence.toString().trim();
                message = message.replaceAll("\n\n+", "\n\n");
                message = message.replaceAll(" +", " ");
                sendButton.setEnabled(message.length() != 0);
                checkSendButton();

                if (message.length() != 0 && lastTypingTimeSend < System.currentTimeMillis() - 5000
                        && !ignoreTextChange) {
                    int currentTime = ConnectionsManager.Instance.getCurrentTime();
                    if (currentUser != null && currentUser.status != null
                            && currentUser.status.expires < currentTime
                            && currentUser.status.was_online < currentTime) {
                        return;
                    }
                    lastTypingTimeSend = System.currentTimeMillis();
                    MessagesController.Instance.sendTyping(dialog_id, classGuid);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (sendByEnter && editable.length() > 0 && editable.charAt(editable.length() - 1) == '\n') {
                    sendMessage();
                }
                int i = 0;
                ImageSpan[] arrayOfImageSpan = editable.getSpans(0, editable.length(), ImageSpan.class);
                int j = arrayOfImageSpan.length;
                while (true) {
                    if (i >= j) {
                        Emoji.replaceEmoji(editable);
                        return;
                    }
                    editable.removeSpan(arrayOfImageSpan[i]);
                    i++;
                }
            }
        });

        bottomOverlayChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentChat != null) {
                    MessagesController.Instance.deleteDialog(-currentChat.id, 0, false);
                    finishFragment();
                }
            }
        });

        chatListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mActionMode != null) {
                    processRowSelect(view);
                    return;
                }
                if (!spanClicked(chatListView, view, R.id.chat_message_text)) {
                    createMenu(view, true);
                }
            }
        });

        chatListView.setOnTouchListener(new OnSwipeTouchListener() {
            public void onSwipeRight() {
                try {
                    if (visibleDialog != null) {
                        visibleDialog.dismiss();
                        visibleDialog = null;
                    }
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                finishFragment(true);
            }

            public void onSwipeLeft() {
                if (swipeOpening) {
                    return;
                }
                try {
                    if (visibleDialog != null) {
                        visibleDialog.dismiss();
                        visibleDialog = null;
                    }
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                if (avatarImageView != null) {
                    swipeOpening = true;
                    avatarImageView.performClick();
                }
            }

            @Override
            public void onTouchUp(MotionEvent event) {
                mLastTouch.right = (int) event.getX();
                mLastTouch.bottom = (int) event.getY();
            }
        });

        emptyView.setOnTouchListener(new OnSwipeTouchListener() {
            public void onSwipeRight() {
                finishFragment(true);
            }

            public void onSwipeLeft() {
                if (swipeOpening) {
                    return;
                }
                if (avatarImageView != null) {
                    swipeOpening = true;
                    avatarImageView.performClick();
                }
            }
        });
        if (currentChat != null && (currentChat instanceof TLRPC.TL_chatForbidden || currentChat.left)) {
            bottomOverlayChat.setVisibility(View.VISIBLE);
        } else {
            bottomOverlayChat.setVisibility(View.GONE);
        }
    } else {
        ViewGroup parent = (ViewGroup) fragmentView.getParent();
        if (parent != null) {
            parent.removeView(fragmentView);
        }
    }
    return fragmentView;
}