Example usage for android.view KeyEvent ACTION_DOWN

List of usage examples for android.view KeyEvent ACTION_DOWN

Introduction

In this page you can find the example usage for android.view KeyEvent ACTION_DOWN.

Prototype

int ACTION_DOWN

To view the source code for android.view KeyEvent ACTION_DOWN.

Click Source Link

Document

#getAction value: the key has been pressed down.

Usage

From source file:com.android.mail.ui.ConversationListFragment.java

@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
    if (view instanceof SwipeableListView) {
        SwipeableListView list = (SwipeableListView) view;
        // Don't need to handle ENTER because it's auto-handled as a "click".
        if (KeyboardUtils.isKeycodeDirectionEnd(keyCode, ViewUtils.isViewRtl(list))) {
            if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
                if (mKeyInitiatedFromList) {
                    int currentPos = list.getSelectedItemPosition();
                    if (currentPos < 0) {
                        // Find the activated item if the focused item is non-existent.
                        // This can happen when the user transitions from touch mode.
                        currentPos = list.getCheckedItemPosition();
                    }/*  www . j ava  2 s .  c om*/
                    if (currentPos >= 0) {
                        // We don't use onListItemSelected because right arrow should always
                        // view the conversation even in CAB/no_sender_image mode.
                        viewConversation(currentPos);
                        commitDestructiveActions(
                                Utils.useTabletUI(mActivity.getActivityContext().getResources()));
                    }
                }
                mKeyInitiatedFromList = false;
            } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                mKeyInitiatedFromList = true;
            }
            return true;
        } else if ((keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
                && keyEvent.getAction() == KeyEvent.ACTION_UP) {
            final int position = list.getSelectedItemPosition();
            if (position >= 0) {
                final Object item = getAnimatedAdapter().getItem(position);
                if (item != null && item instanceof ConversationCursor) {
                    final Conversation conv = ((ConversationCursor) item).getConversation();
                    mCallbacks.onConversationFocused(conv);
                }
            }
        }
    }
    return false;
}

From source file:android.support.v7.app.AppCompatDelegateImplV7.java

@Override
boolean dispatchKeyEvent(KeyEvent event) {
    final int keyCode = event.getKeyCode();
    final int action = event.getAction();
    final boolean isDown = action == KeyEvent.ACTION_DOWN;

    return isDown ? onKeyDown(keyCode, event) : onKeyUp(keyCode, event);
}

From source file:com.jamiealtizer.cordova.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/*from ww w  . ja  va  2 s .  com*/
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    showZoomControls = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean zoom = features.get(ZOOM);
        if (zoom != null) {
            showZoomControls = zoom.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
        if (hardwareBack != null) {
            hadwareBackButton = hardwareBack.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        @SuppressLint("NewApi")
        public void run() {
            // Let's create the main dialog
            final Context ctx = cordova.getActivity();
            dialog = new InAppBrowserDialog(ctx, android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setInAppBroswer(getInAppBrowser());

            // Main container layout
            LinearLayout main = new LinearLayout(ctx);
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(ctx);
            //Please, no more black!
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY); // JAMIE REVIEW
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.CENTER_VERTICAL);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(ctx);
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            final ButtonAwesome back = new ButtonAwesome(ctx);
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setBackgroundResource(ExternalResourceHelper.getDrawable(ctx, "buttonbackground"));
            back.setTextColor(ExternalResourceHelper.getColor(ctx, "gray"));
            back.setText(ExternalResourceHelper.getStrings(ctx, "fa_chevron_left"));
            back.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
            //            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
            //                {
            //                    back.setBackgroundDrawable(backIcon);
            //                }
            //                else
            //                {
            //                    back.setBackground(backIcon);
            //                }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            final ButtonAwesome forward = new ButtonAwesome(ctx);
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setBackgroundResource(ExternalResourceHelper.getDrawable(ctx, "buttonbackground"));
            forward.setTextColor(ExternalResourceHelper.getColor(ctx, "gray"));
            forward.setText(ExternalResourceHelper.getStrings(ctx, "fa_chevron_right"));
            forward.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
            //            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
            //                {
            //                    forward.setBackgroundDrawable(fwdIcon);
            //                }
            //                else
            //                {
            //                    forward.setBackground(fwdIcon);
            //                }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // external button
            ButtonAwesome external = new ButtonAwesome(ctx);
            RelativeLayout.LayoutParams externalLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            externalLayoutParams.addRule(RelativeLayout.RIGHT_OF, 3);
            external.setLayoutParams(externalLayoutParams);
            external.setContentDescription("Back Button");
            external.setId(7);
            external.setBackgroundResource(ExternalResourceHelper.getDrawable(ctx, "buttonbackground"));
            external.setTextColor(ExternalResourceHelper.getColor(ctx, "white"));
            external.setText(ExternalResourceHelper.getStrings(ctx, "fa_external_link"));
            external.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
            external.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    openExternal(edittext.getText().toString());
                    closeDialog();
                }
            });

            // Edit Text Box
            edittext = new EditText(ctx);
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    if (s.length() > 0) {
                        if (inAppWebView.canGoBack()) {
                            back.setTextColor(ExternalResourceHelper.getColor(ctx, "white"));
                        } else {
                            back.setTextColor(ExternalResourceHelper.getColor(ctx, "gray"));
                        }
                        if (inAppWebView.canGoForward()) {
                            forward.setTextColor(ExternalResourceHelper.getColor(ctx, "white"));
                        } else {
                            forward.setTextColor(ExternalResourceHelper.getColor(ctx, "gray"));
                        }
                    }
                }

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

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close/Done button
            ButtonAwesome close = new ButtonAwesome(ctx);
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            close.setContentDescription("Close Button");
            close.setId(5);
            close.setBackgroundResource(ExternalResourceHelper.getDrawable(ctx, "buttonbackground"));
            close.setText(ExternalResourceHelper.getStrings(ctx, "fa_times"));
            close.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
            close.setTextColor(ExternalResourceHelper.getColor(ctx, "white"));
            //            if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN)
            //                {
            //                    close.setBackgroundDrawable(closeIcon);
            //                }
            //                else
            //                {
            //                    close.setBackground(closeIcon);
            //                }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(ctx);
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(showZoomControls);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = ctx.getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE)
                        .getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);
            actionButtonContainer.addView(external);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            if (getShowLocationBar()) {
                toolbar.addView(edittext);
            }
            toolbar.setBackgroundColor(ExternalResourceHelper.getColor(ctx, "green"));
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            //if (getShowLocationBar()) {
            // Add our toolbar to our main view/layout
            main.addView(toolbar);
            //}

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:info.guardianproject.otr.app.im.app.ChatView.java

@Override
protected void onFinishInflate() {
    //  mStatusIcon = (ImageView) findViewById(R.id.statusIcon);
    //   mDeliveryIcon = (ImageView) findViewById(R.id.deliveryIcon);
    // mTitle = (TextView) findViewById(R.id.title);
    mHistory = (ListView) findViewById(R.id.history);
    mComposeMessage = (EditText) findViewById(R.id.composeMessage);
    mSendButton = (ImageButton) findViewById(R.id.btnSend);
    mHistory.setOnItemClickListener(mOnItemClickListener);
    mButtonAttach = (ImageButton) findViewById(R.id.btnAttach);
    mViewAttach = findViewById(R.id.attachPanel);

    mStatusWarningView = findViewById(R.id.warning);
    mWarningText = (TextView) findViewById(R.id.warningText);

    mProgressTransfer = (ProgressBar) findViewById(R.id.progressTransfer);
    // mOtrSwitch = (CompoundButton)findViewById(R.id.otrSwitch);
    mProgressBarOtr = (ProgressBar) findViewById(R.id.progressBarOtr);

    mButtonAttach.setOnClickListener(new OnClickListener() {

        @Override//  w  ww  . j a  v  a 2s .c o  m
        public void onClick(View v) {

            if (mViewAttach.getVisibility() == View.GONE)
                mViewAttach.setVisibility(View.VISIBLE);
            else
                mViewAttach.setVisibility(View.GONE);
        }

    });

    ((ImageButton) findViewById(R.id.btnAttachAudio)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            mNewChatActivity.startAudioPicker();
        }

    });

    ((ImageButton) findViewById(R.id.btnAttachPicture)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            mNewChatActivity.startImagePicker();
        }

    });

    ((ImageButton) findViewById(R.id.btnTakePicture)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            mNewChatActivity.startPhotoTaker();
        }

    });

    ((ImageButton) findViewById(R.id.btnAttachFile)).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            mNewChatActivity.startFilePicker();
        }

    });

    mHistory.setOnItemLongClickListener(new OnItemLongClickListener() {

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            if (arg1 instanceof MessageView) {

                String textToCopy = ((MessageView) arg1).getLastMessage();

                int sdk = android.os.Build.VERSION.SDK_INT;
                if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
                    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) mNewChatActivity
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setText(textToCopy); //
                } else {
                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) mNewChatActivity
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    android.content.ClipData clip = android.content.ClipData.newPlainText("chat", textToCopy);
                    clipboard.setPrimaryClip(clip); //
                }

                Toast.makeText(mNewChatActivity, mContext.getString(R.string.toast_chat_copied_to_clipboard),
                        Toast.LENGTH_SHORT).show();

                return true;

            }

            return false;
        }

    });

    mWarningText.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            showVerifyDialog();
        }
    });

    //mOtrSwitch.setOnCheckedChangeListener(mOtrListener);

    mComposeMessage.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                    sendMessage();
                    return true;

                case KeyEvent.KEYCODE_ENTER:
                    if (event.isAltPressed()) {
                        mComposeMessage.append("\n");
                        return true;
                    }
                }
            }
            return false;
        }
    });

    mComposeMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (event != null) {
                if (event.isAltPressed()) {
                    return false;
                }
            }

            InputMethodManager imm = (InputMethodManager) mContext
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null && imm.isActive(v)) {
                imm.hideSoftInputFromWindow(getWindowToken(), 0);
            }
            sendMessage();
            return true;
        }
    });

    // TODO: this is a hack to implement BUG #1611278, when dispatchKeyEvent() works with
    // the soft keyboard, we should remove this hack.
    mComposeMessage.addTextChangedListener(new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int before, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int after) {
            //log("TextWatcher: " + s);
            userActionDetected();
        }

        public void afterTextChanged(Editable s) {
        }
    });

    mSendButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            sendMessage();
        }
    });

    Button btnApproveSubscription = (Button) findViewById(R.id.btnApproveSubscription);
    btnApproveSubscription.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            mNewChatActivity.approveSubscription(mProviderId, mRemoteAddress);

            mHandler.postDelayed(new Runnable() {
                public void run() {
                    bindChat(mLastChatId);
                }
            }, 2000);

        }

    });

    Button btnDeclineSubscription = (Button) findViewById(R.id.btnDeclineSubscription);
    btnDeclineSubscription.setOnClickListener(new OnClickListener() {

        @Override

        public void onClick(View v) {

            mHandler.postDelayed(new Runnable() {
                public void run() {
                    mNewChatActivity.declineSubscription(mProviderId, mRemoteAddress);

                }
            }, 500);

        }

    });

    /*
    mActionBox = (View)findViewById(R.id.actionBox);
    ImageButton btnActionBox = (ImageButton)findViewById(R.id.btnActionBox);
    btnActionBox.setOnClickListener(new OnClickListener ()
    {
            
    @Override
    public void onClick(View v) {
            
        mEmojiPager.setVisibility(View.GONE);
            
            
        if (mActionBox.getVisibility() == View.GONE)
            mActionBox.setVisibility(View.VISIBLE);
        else
            mActionBox.setVisibility(View.GONE);
    }
            
    });
            
    View btnEndChat = findViewById(R.id.btnEndChat);
    btnEndChat.setOnClickListener(new OnClickListener ()
    {
            
    @Override
    public void onClick(View v) {
            
        ChatView.this.closeChatSession();
    }
            
    });
            
    View btnProfile = findViewById(R.id.btnProfile);
    btnProfile.setOnClickListener(new OnClickListener ()
    {
            
    @Override
    public void onClick(View v) {
            
        viewProfile();
    }
            
    });
            
    View btnSharePicture = findViewById(R.id.btnSendPicture);
    btnSharePicture.setOnClickListener(new OnClickListener ()
    {
            
    @Override
    public void onClick(View v) {
            
        if (mLastSessionStatus != null && mLastSessionStatus == SessionStatus.ENCRYPTED)
        {
            mNewChatActivity.startImagePicker();
        }
        else
        {
            mHandler.showServiceErrorAlert(getContext().getString(R.string.please_enable_chat_encryption_to_share_files));
        }
    }
            
    });
            
    View btnShareFile = findViewById(R.id.btnSendFile);
    btnShareFile.setOnClickListener(new OnClickListener ()
    {
            
    @Override
    public void onClick(View v) {
            
        if (mLastSessionStatus != null && mLastSessionStatus == SessionStatus.ENCRYPTED)
        {
            mNewChatActivity.startFilePicker();
        }
        else
        {
            mHandler.showServiceErrorAlert(getContext().getString(R.string.please_enable_chat_encryption_to_share_files));
            
        }
    }
            
    });
    */

    initEmoji();

    mMessageAdapter = new MessageAdapter(mNewChatActivity, null);
    mHistory.setAdapter(mMessageAdapter);
}

From source file:com.example.innf.newchangtu.Map.view.activity.MainActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    sendSMSTime = System.currentTimeMillis();/*?*/
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {//  w ww  .  j a v a  2  s  . c om
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            AlertDialog dialog = builder.setTitle(R.string.app_name).setIcon(R.mipmap.ic_launcher)
                    .setMessage("?")
                    .setPositiveButton("", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                            System.exit(0);
                        }
                    }).setNegativeButton("?", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    }).show();
        }
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_POWER && event.getAction() == KeyEvent.ACTION_DOWN) {
        if ((System.currentTimeMillis() - sendSMSTime) < 2000) {
            powerButtonClickTimes++;
            if (powerButtonClickTimes == 4) {
                Log.d(TAG, powerButtonClickTimes + "");
                showToast("???");
            }
        } else {
            powerButtonClickTimes = 0;
        }
    }
    return super.onKeyDown(keyCode, event);
}

From source file:com.shafiq.mytwittle.view.BaseLaneActivity.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            if (AppSettings.get().isVolScrollEnabled()) {
                Intent intent = new Intent("" + SystemEvent.VOLUME_UP_KEY_DOWN);
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
                return true;
            }//from  www . j  a  v  a2 s  . c om

        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            if (AppSettings.get().isVolScrollEnabled()) {
                Intent intent = new Intent("" + SystemEvent.VOLUME_DOWN_KEY_DOWN);
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
                return true;
            }
        }
    }

    return super.onKeyDown(keyCode, event);
}

From source file:com.kaichaohulian.baocms.ecdemo.ui.chatting.ChattingFragment.java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        LogUtil.d(TAG, "keycode back , chatfooter mode: " + mChattingFooter.getMode());
        if (!mChattingFooter.isButtomPanelNotVisibility()) {
            hideBottom();//from w w  w  . j av  a  2  s  .  c  o m
            return true;
        }
        setIsFinish(true);
    } else if (keyCode == KeyEvent.KEYCODE_DEL) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            mHandlerDelChar = !(mChattingFooter.getCharAtCursor() != (char) (8197));
        }
        if (event.getAction() == KeyEvent.ACTION_UP && mHandlerDelChar) {
            mHandlerDelChar = false;
            CCPChattingFooter2 footer = this.mChattingFooter;
            int selectionStart = footer.getSelectionStart();
            String text = footer.getLastText().substring(0, selectionStart);
            int atIndex = text.lastIndexOf('@');
            if (atIndex < text.length() && atIndex >= 0) {
                delAtSomeBody(text.substring(atIndex, selectionStart));
                String subStartText = text.substring(0, atIndex);
                String subSecondText = footer.getLastText().substring(selectionStart);
                StringBuilder sb = new StringBuilder();
                sb.append(subStartText).append(subSecondText);
                footer.setLastText(sb.toString());
                footer.mEditText.setSelection(atIndex);
            }
        }
    }
    return super.onKeyDown(keyCode, event);
}

From source file:research.sg.edu.edapp.kb.KbSoftKeyboard.java

/**
 * Helper to send a key down / key up pair to the current editor.
 */// w  w w.j  av  a2  s.c  o m
private void keyDownUp(int keyEventCode) {
    System.out.print("came");

    getCurrentInputConnection().sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode));
    getCurrentInputConnection().sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyEventCode));
}

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();/*from   www . j  a va  2s  .  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 .  j  a v a  2 s  . c  om
    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);
}