Example usage for android.view.inputmethod EditorInfo IME_ACTION_SEND

List of usage examples for android.view.inputmethod EditorInfo IME_ACTION_SEND

Introduction

In this page you can find the example usage for android.view.inputmethod EditorInfo IME_ACTION_SEND.

Prototype

int IME_ACTION_SEND

To view the source code for android.view.inputmethod EditorInfo IME_ACTION_SEND.

Click Source Link

Document

Bits of #IME_MASK_ACTION : the action key performs a "send" operation, delivering the text to its target.

Usage

From source file:com.ieeton.agency.activity.ChatActivity.java

/**
 * initView//from  w w w. j a  v  a  2 s .co  m
 */
protected void initView() {
    recordingContainer = findViewById(R.id.recording_container);
    micImage = (ImageView) findViewById(R.id.mic_image);
    recordingHint = (TextView) findViewById(R.id.recording_hint);
    listView = (ListView) findViewById(R.id.list);
    mEditTextContent = (PasteEditText) findViewById(R.id.et_sendmessage);
    buttonSetModeKeyboard = findViewById(R.id.btn_set_mode_keyboard);
    edittext_layout = (RelativeLayout) findViewById(R.id.edittext_layout);
    buttonSetModeVoice = findViewById(R.id.btn_set_mode_voice);
    mBtnQuick = (Button) findViewById(R.id.btn_quick_reply);
    buttonPressToSpeak = findViewById(R.id.btn_press_to_speak);
    expressionViewpager = (ViewPager) findViewById(R.id.vPager);
    expressionContainer = (LinearLayout) findViewById(R.id.ll_face_container);
    btnContainer = (LinearLayout) findViewById(R.id.ll_btn_container);
    locationImgview = (ImageView) findViewById(R.id.btn_location);
    //iv_emoticons_normal = (ImageView) findViewById(R.id.iv_emoticons_normal);
    //iv_emoticons_checked = (ImageView) findViewById(R.id.iv_emoticons_checked);
    loadmorePB = (ProgressBar) findViewById(R.id.pb_load_more);
    buttonSend = findViewById(R.id.btn_send);
    //btnMore = (Button) findViewById(R.id.btn_more);
    //iv_emoticons_normal.setVisibility(View.VISIBLE);
    //iv_emoticons_checked.setVisibility(View.INVISIBLE);
    more = findViewById(R.id.more);
    //edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_normal);

    mTitleName = (TextView) findViewById(R.id.name);
    mBtnAdd = (ImageButton) findViewById(R.id.iv_add);
    mBtnAdd.setOnClickListener(this);
    mBtnCall = (ImageButton) findViewById(R.id.iv_call);
    mBtnCall.setOnClickListener(this);
    mBtnShare = (ImageButton) findViewById(R.id.iv_share);
    mBtnShare.setOnClickListener(this);
    mBtnPhoto = (Button) findViewById(R.id.btn_photo);
    mBtnPhoto.setOnClickListener(this);
    mBtnQuick.setOnClickListener(this);
    buttonSend.setOnClickListener(this);
    mBackBtn = (LinearLayout) findViewById(R.id.ll_back);
    mBackBtn.setOnClickListener(this);

    // ?,
    micImages = new Drawable[] { getResources().getDrawable(R.drawable.record_animate_01),
            getResources().getDrawable(R.drawable.record_animate_02),
            getResources().getDrawable(R.drawable.record_animate_03),
            getResources().getDrawable(R.drawable.record_animate_04),
            getResources().getDrawable(R.drawable.record_animate_05),
            getResources().getDrawable(R.drawable.record_animate_06),
            getResources().getDrawable(R.drawable.record_animate_07),
            getResources().getDrawable(R.drawable.record_animate_08),
            getResources().getDrawable(R.drawable.record_animate_09),
            getResources().getDrawable(R.drawable.record_animate_10),
            getResources().getDrawable(R.drawable.record_animate_11),
            getResources().getDrawable(R.drawable.record_animate_12),
            getResources().getDrawable(R.drawable.record_animate_13),
            getResources().getDrawable(R.drawable.record_animate_14), };
    // list
    reslist = getExpressionRes(35);
    // ?viewpager
    List<View> views = new ArrayList<View>();
    View gv1 = getGridChildView(1);
    View gv2 = getGridChildView(2);
    views.add(gv1);
    views.add(gv2);
    expressionViewpager.setAdapter(new ExpressionPagerAdapter(views));
    edittext_layout.requestFocus();
    voiceRecorder = new VoiceRecorder(micImageHandler);
    buttonPressToSpeak.setOnTouchListener(new PressToSpeakListen());
    //      mEditTextContent.setOnFocusChangeListener(new OnFocusChangeListener() {
    //
    //         @Override
    //         public void onFocusChange(View v, boolean hasFocus) {
    //            if (hasFocus) {
    //               edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_active);
    //            } else {
    //               edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_normal);
    //            }
    //
    //         }
    //      });
    mEditTextContent.setImeOptions(EditorInfo.IME_ACTION_SEND);
    mEditTextContent.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            switch (actionId) {
            case EditorInfo.IME_ACTION_UNSPECIFIED:
            case EditorInfo.IME_ACTION_SEND:
                String s = mEditTextContent.getText().toString();
                sendText(s);
                return true;
            default:
                return false;
            }
        }
    });

    mEditTextContent.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //edittext_layout.setBackgroundResource(R.drawable.input_bar_bg_active);
            more.setVisibility(View.GONE);
            //iv_emoticons_normal.setVisibility(View.VISIBLE);
            //iv_emoticons_checked.setVisibility(View.INVISIBLE);
            expressionContainer.setVisibility(View.GONE);
            btnContainer.setVisibility(View.GONE);
        }
    });
    // ?
    mEditTextContent.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!TextUtils.isEmpty(s)) {
                mBtnQuick.setVisibility(View.GONE);
                buttonSend.setVisibility(View.VISIBLE);
            } else {
                mBtnQuick.setVisibility(View.VISIBLE);
                buttonSend.setVisibility(View.GONE);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

}

From source file:de.azapps.mirakel.helper.TaskDialogHelpers.java

@SuppressLint("NewApi")
public static void handleSubtask(final Context ctx, final Task task, final OnTaskChangedListner taskChanged,
        final boolean asSubtask) {
    final List<Pair<Long, String>> names = Task.getTaskNames();
    final CharSequence[] values = new String[names.size()];
    for (int i = 0; i < names.size(); i++) {
        values[i] = names.get(i).second;
    }//from   w  w w  . j a va  2 s  . com
    final View v = ((Activity) ctx).getLayoutInflater().inflate(R.layout.select_subtask, null, false);
    final ListView lv = (ListView) v.findViewById(R.id.subtask_listview);
    final List<Task> tasks = Task.cursorToTaskList(
            ctx.getContentResolver().query(MirakelInternalContentProvider.TASK_URI, Task.allColumns,
                    ModelBase.ID + "=" + task.getId() + " AND " + Task.BASIC_FILTER_DISPLAY_TASKS, null, null));
    subtaskAdapter = new SubtaskAdapter(ctx, 0, tasks, task, asSubtask);
    lv.post(new Runnable() {
        @Override
        public void run() {
            lv.setAdapter(subtaskAdapter);
        }
    });
    searchString = "";
    done = false;
    content = false;
    reminder = false;
    optionEnabled = false;
    newTask = true;
    listId = SpecialList.firstSpecialSafe().getId();
    final EditText search = (EditText) v.findViewById(R.id.subtask_searchbox);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        Drawable left = ctx.getResources().getDrawable(android.R.drawable.ic_menu_search);
        Drawable right = null;
        left.setBounds(0, 0, 42, 42);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
                && ctx.getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL) {
            right = ctx.getResources().getDrawable(android.R.drawable.ic_menu_search);
            right.setBounds(0, 0, 42, 42);
            left = null;
        }
        search.setCompoundDrawables(left, null, right, null);
    }
    search.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(final Editable s) {
            // Nothing
        }

        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
            // Nothing
        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
            searchString = s.toString();
            updateListView(subtaskAdapter, task, lv, ctx);
        }
    });
    final Button options = (Button) v.findViewById(R.id.subtasks_options);
    final LinearLayout wrapper = (LinearLayout) v.findViewById(R.id.subtask_option_wrapper);
    wrapper.setVisibility(View.GONE);
    options.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (optionEnabled) {
                wrapper.setVisibility(View.GONE);
            } else {
                wrapper.setVisibility(View.VISIBLE);
                final InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
            }
            optionEnabled = !optionEnabled;
        }
    });
    final ViewSwitcher switcher = (ViewSwitcher) v.findViewById(R.id.subtask_switcher);
    final Button subtaskNewtask = (Button) v.findViewById(R.id.subtask_newtask);
    final Button subtaskSelectOld = (Button) v.findViewById(R.id.subtask_select_old);
    final boolean darkTheme = MirakelCommonPreferences.isDark();
    if (asSubtask) {
        v.findViewById(R.id.subtask_header).setVisibility(View.GONE);
        switcher.showNext();
        newTask = false;
    } else {
        subtaskNewtask.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (newTask) {
                    return;
                }
                switcher.showPrevious();
                subtaskNewtask
                        .setTextColor(ctx.getResources().getColor(darkTheme ? R.color.White : R.color.Black));
                subtaskSelectOld.setTextColor(ctx.getResources().getColor(R.color.Grey));
                newTask = true;
            }
        });
        subtaskSelectOld.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (!newTask) {
                    return;
                }
                switcher.showNext();
                subtaskNewtask.setTextColor(ctx.getResources().getColor(R.color.Grey));
                subtaskSelectOld
                        .setTextColor(ctx.getResources().getColor(darkTheme ? R.color.White : R.color.Black));
                if (subtaskAdapter != null) {
                    subtaskAdapter.notifyDataSetChanged();
                }
                newTask = false;
                lv.invalidateViews();
                updateListView(subtaskAdapter, task, lv, ctx);
            }
        });
    }
    final CheckBox doneBox = (CheckBox) v.findViewById(R.id.subtask_done);
    doneBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            done = isChecked;
            updateListView(subtaskAdapter, task, lv, ctx);
        }
    });
    final CheckBox reminderBox = (CheckBox) v.findViewById(R.id.subtask_reminder);
    reminderBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            reminder = isChecked;
            updateListView(subtaskAdapter, task, lv, ctx);
        }
    });
    final Button list = (Button) v.findViewById(R.id.subtask_list);
    list.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            final List<ListMirakel> lists = ListMirakel.all(true);
            final CharSequence[] names = new String[lists.size()];
            for (int i = 0; i < names.length; i++) {
                names[i] = lists.get(i).getName();
            }
            new AlertDialog.Builder(ctx).setSingleChoiceItems(names, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    listId = lists.get(which).getId();
                    updateListView(subtaskAdapter, task, lv, ctx);
                    list.setText(lists.get(which).getName());
                    dialog.dismiss();
                }
            }).show();
        }
    });
    final CheckBox contentBox = (CheckBox) v.findViewById(R.id.subtask_content);
    contentBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
            content = isChecked;
            updateListView(subtaskAdapter, task, lv, ctx);
        }
    });
    final EditText newTaskEdit = (EditText) v.findViewById(R.id.subtask_add_task_edit);
    final AlertDialog dialog = new AlertDialog.Builder(ctx).setTitle(ctx.getString(R.string.add_subtask))
            .setView(v).setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    if (newTask && newTaskEdit.getText().length() > 0) {
                        newSubtask(newTaskEdit.getText().toString(), task, ctx);
                    } else if (!newTask) {
                        final List<Task> checked = subtaskAdapter.getSelected();
                        for (final Task t : checked) {
                            if (!asSubtask) {
                                if (!t.hasSubtasksLoop(task)) {
                                    task.addSubtask(t);
                                } else {
                                    ErrorReporter.report(ErrorType.TASKS_CANNOT_FORM_LOOP);
                                }
                            } else {
                                if (!task.hasSubtasksLoop(t)) {
                                    t.addSubtask(task);
                                } else {
                                    ErrorReporter.report(ErrorType.TASKS_CANNOT_FORM_LOOP);
                                }
                            }
                        }
                    }
                    if (taskChanged != null) {
                        taskChanged.onTaskChanged(task);
                    }
                    ((Activity) ctx).getWindow()
                            .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                    dialog.dismiss();
                }
            }).setNegativeButton(android.R.string.cancel, dialogDoNothing).show();
    newTaskEdit.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                newSubtask(v.getText().toString(), task, ctx);
                v.setText(null);
                if (taskChanged != null) {
                    taskChanged.onTaskChanged(task);
                }
                dialog.dismiss();
            }
            return 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();/* ww  w.  j a  v  a 2  s  . c  om*/

        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;
}

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. ja v a 2 s. 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.thoughtcrime.securesms.ConversationActivity.java

private void initializeIme() {
    if (TextSecurePreferences.isEnterSendsEnabled(this)) {
        composeText.setInputType(composeText.getInputType() & ~InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        composeText.setImeOptions(composeText.getImeOptions() & ~EditorInfo.IME_FLAG_NO_ENTER_ACTION);
    } else {//from  w  w w  . j  a  v  a2  s .  c  om
        composeText.setInputType(composeText.getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        composeText.setImeOptions(composeText.getImeOptions() | EditorInfo.IME_FLAG_NO_ENTER_ACTION);
    }
    composeText.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                sendMessage();
                return true;
            }
            return false;
        }
    });
}

From source file:org.thoughtcrime.securesms.ConversationActivity.java

private void initializeViews() {
    titleView = (ConversationTitleView) getSupportActionBar().getCustomView();
    buttonToggle = (AnimatingToggle) findViewById(R.id.button_toggle);
    sendButton = (SendButton) findViewById(R.id.send_button);
    attachButton = (ImageButton) findViewById(R.id.attach_button);
    composeText = (ComposeText) findViewById(R.id.embedded_text_editor);
    charactersLeft = (TextView) findViewById(R.id.space_left);
    emojiToggle = (EmojiToggle) findViewById(R.id.emoji_toggle);
    unblockButton = (Button) findViewById(R.id.unblock_button);
    composePanel = findViewById(R.id.bottom_panel);
    composeBubble = findViewById(R.id.compose_bubble);
    container = (KeyboardAwareLinearLayout) findViewById(R.id.layout_container);

    container.addOnKeyboardShownListener(this);

    buttonToggle = (AnimatingToggle) findViewById(R.id.button_toggle);
    sendButton = (SendButton) findViewById(R.id.send_button);
    attachButton = (ImageButton) findViewById(R.id.attach_button);
    composeText = (ComposeText) findViewById(R.id.embedded_text_editor);
    charactersLeft = (TextView) findViewById(R.id.space_left);
    emojiToggle = (EmojiToggle) findViewById(R.id.emoji_toggle);
    titleView = (ConversationTitleView) getSupportActionBar().getCustomView();
    unblockButton = (Button) findViewById(R.id.unblock_button);
    composePanel = findViewById(R.id.bottom_panel);
    quickAttachmentDrawer = (QuickAttachmentDrawer) findViewById(R.id.quick_attachment_drawer);
    quickAttachmentToggle = (HidingImageButton) findViewById(R.id.quick_attachment_toggle);

    int[] attributes = new int[] { R.attr.conversation_item_bubble_background };
    TypedArray colors = obtainStyledAttributes(attributes);
    int defaultColor = colors.getColor(0, Color.WHITE);
    composeBubble.getBackground().setColorFilter(defaultColor, PorterDuff.Mode.MULTIPLY);
    colors.recycle();//from w  ww .  j  ava2 s .c  o  m

    attachmentAdapter = new AttachmentTypeSelectorAdapter(this);
    attachmentManager = new AttachmentManager(this, this);

    SendButtonListener sendButtonListener = new SendButtonListener();
    ComposeKeyPressedListener composeKeyPressedListener = new ComposeKeyPressedListener();

    attachButton.setOnClickListener(new AttachButtonListener());
    sendButton.setOnClickListener(sendButtonListener);
    sendButton.setEnabled(true);
    sendButton.addOnTransportChangedListener(new OnTransportChangedListener() {
        @Override
        public void onChange(TransportOption newTransport) {
            calculateCharactersRemaining();
            composeText.setHint(newTransport.getComposeHint());
            composeText.setImeActionLabel(newTransport.getComposeHint(), EditorInfo.IME_ACTION_SEND);
            composeText.setInputType(composeText.getInputType());
            buttonToggle.getBackground().setColorFilter(newTransport.getBackgroundColor(), Mode.MULTIPLY);
        }
    });

    titleView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(ConversationActivity.this, RecipientPreferenceActivity.class);
            intent.putExtra(RecipientPreferenceActivity.RECIPIENTS_EXTRA, recipients.getIds());

            startActivitySceneTransition(intent, titleView.findViewById(R.id.title), "recipient_name");
        }
    });

    unblockButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            handleUnblock();
        }
    });

    composeText.setOnKeyListener(composeKeyPressedListener);
    composeText.addTextChangedListener(composeKeyPressedListener);
    composeText.setOnEditorActionListener(sendButtonListener);
    composeText.setOnClickListener(composeKeyPressedListener);
    composeText.setOnFocusChangeListener(composeKeyPressedListener);
    emojiToggle.setOnClickListener(new EmojiToggleListener());

    if (QuickAttachmentDrawer.isDeviceSupported(this)) {
        quickAttachmentDrawer.setListener(this);
        quickAttachmentToggle.setOnClickListener(new QuickAttachmentToggleListener());
    } else {
        quickAttachmentToggle.disable();
    }
}

From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardViewBase.java

@NonNull
private CharSequence guessLabelForKey(int keyCode) {
    switch (keyCode) {
    case KeyCodes.ENTER:
        switch (mKeyboardActionType) {
        case EditorInfo.IME_ACTION_DONE:
            return getContext().getText(R.string.label_done_key);
        case EditorInfo.IME_ACTION_GO:
            return getContext().getText(R.string.label_go_key);
        case EditorInfo.IME_ACTION_NEXT:
            return getContext().getText(R.string.label_next_key);
        case 0x00000007:// API 11: EditorInfo.IME_ACTION_PREVIOUS:
            return getContext().getText(R.string.label_previous_key);
        case EditorInfo.IME_ACTION_SEARCH:
            return getContext().getText(R.string.label_search_key);
        case EditorInfo.IME_ACTION_SEND:
            return getContext().getText(R.string.label_send_key);
        default:// w  w  w. j a v a  2s.c  o m
            return "";
        }
    case KeyCodes.KEYBOARD_MODE_CHANGE:
        if (mKeyboard instanceof GenericKeyboard)
            return guessLabelForKey(KeyCodes.MODE_ALPHABET);
        else
            return guessLabelForKey(KeyCodes.MODE_SYMOBLS);
    case KeyCodes.MODE_ALPHABET:
        return mNextAlphabetKeyboardName;
    case KeyCodes.MODE_SYMOBLS:
        return mNextSymbolsKeyboardName;
    case KeyCodes.TAB:
        return getContext().getText(R.string.label_tab_key);
    case KeyCodes.MOVE_HOME:
        return getContext().getText(R.string.label_home_key);
    case KeyCodes.MOVE_END:
        return getContext().getText(R.string.label_end_key);
    case KeyCodes.ARROW_DOWN:
        return "";
    case KeyCodes.ARROW_LEFT:
        return "";
    case KeyCodes.ARROW_RIGHT:
        return "";
    case KeyCodes.ARROW_UP:
        return "";
    default:
        return "";
    }
}

From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardBaseView.java

private CharSequence guessLabelForKey(int keyCode) {
    switch (keyCode) {
    case KeyCodes.ENTER:
        switch (mKeyboardActionType) {
        case EditorInfo.IME_ACTION_DONE:
            return getContext().getText(R.string.label_done_key);
        case EditorInfo.IME_ACTION_GO:
            return getContext().getText(R.string.label_go_key);
        case EditorInfo.IME_ACTION_NEXT:
            return getContext().getText(R.string.label_next_key);
        case 0x00000007:// API 11: EditorInfo.IME_ACTION_PREVIOUS:
            return getContext().getText(R.string.label_previous_key);
        case EditorInfo.IME_ACTION_SEARCH:
            return getContext().getText(R.string.label_search_key);
        case EditorInfo.IME_ACTION_SEND:
            return getContext().getText(R.string.label_send_key);
        default://from ww w  .  j av  a  2s .c  o m
            return "";
        }
    case KeyCodes.KEYBOARD_MODE_CHANGE:
        if (mSwitcher.isAlphabetMode())
            return guessLabelForKey(KeyCodes.MODE_SYMOBLS);
        else
            return guessLabelForKey(KeyCodes.MODE_ALPHABET);
    case KeyCodes.MODE_ALPHABET:
        String langKeyText = null;
        if (mSwitcher != null)//should show the next keyboard label, not a generic one.
            langKeyText = mSwitcher.peekNextAlphabetKeyboard();
        if (langKeyText == null)
            return getResources().getString(R.string.change_lang_regular);
        else
            return langKeyText;
    case KeyCodes.MODE_SYMOBLS:
        String symKeyText = null;
        if (mSwitcher != null)//should show the next keyboard label, not a generic one.
            symKeyText = mSwitcher.peekNextSymbolsKeyboard();
        if (symKeyText == null)
            return getResources().getString(R.string.change_symbols_regular);
        else
            return symKeyText;
    case KeyCodes.TAB:
        return getContext().getText(R.string.label_tab_key);
    case KeyCodes.MOVE_HOME:
        return getContext().getText(R.string.label_home_key);
    case KeyCodes.MOVE_END:
        return getContext().getText(R.string.label_end_key);
    case KeyCodes.ARROW_DOWN:
        return "\u2193";
    case KeyCodes.ARROW_LEFT:
        return "\u2190";
    case KeyCodes.ARROW_RIGHT:
        return "\u2192";
    case KeyCodes.ARROW_UP:
        return "\u2191";
    default:
        return null;
    }
}