Search code examples
androidandroid-activityonbackpressed

Handle back pressed to not dismiss activity


I want to handle back press like whatsapp where while typing if user presses back the keyboard is dismissed and if the user presses back again ,we go to chats tab.In my activity I want that when the user presses back while typing the keyboard dismisses and some UI elements are handled.I tried handling that in the onBackPressed() method , but it isn't working and the activity is killed.

     edittext.setOnEditorActionListener (
                    new EditText.OnEditorActionListener () {
                        @Override
                        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                            if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                                    actionId == EditorInfo.IME_ACTION_DONE ||
                                    event != null &&
                                            event.getAction () == KeyEvent.ACTION_DOWN &&
                                            event.getKeyCode () == KeyEvent.KEYCODE_ENTER) {
                                if (event == null || !event.isShiftPressed ()) {
                                    // the user is done typing.

                                    View view1 = getCurrentFocus ();
                                    imm.hideSoftInputFromWindow (view1.getWindowToken (), 0);

                                    Log.e (TAG, "TYPING DONE ");
                                    result = tv_result.getText ().toString();

                                    return true; // consume.
                                }
                            }
                            return false; // pass on to other listeners.
                        }
                    }
            );

the onBackPressed() code

     @Override
    public void onBackPressed() {

    tv_result.setText("Some text");

}

Solution

  • Since you haven't provided any code, and I can't comment yet, I will assume you're letting the onBackPressed do what it per default does, meaning that in your onBackPressed() method you have super.onBackPressed(); , removing that line should solve the issue

    Edit Since you've updated your question with code, whatever is written after super.onBackPressed() will not be seen visually, as super.onBackPressed() goes back to the previous activity. Remove super.onBackPressed(), and handle the second back press with and if else statement