Search code examples
androidandroid-keypad

onBackPressed method is not working properly


In my app there is one EditText. I have called keypad show on my activity for this EditText. keypad showing & working fine.

Now in currently, I have to press back button two time, one for hiding keypad & another for performing some task(like data saving to DB).I don't want to press back button two times.

please guide me, or suggestion

here some from onBackPressed()

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();

    hideKeypad();

    //saving EditText data to db.
}

code form hideKeypad()

private void hideKeypad() {
       InputMethodManager imm = (InputMethodManager) 
        getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(edittext1.getWindowToken(), 0);
}

Solution

  • Use this method it is similar what you already done but I little modified it . Register listener of your main layout and pass its object as param so that when you click out side of edit text i,e. main layout keypad will gone.

    /** Close Keypad on touch.
     * @param view on which click happens. */
    
     public void closeKeyPad(View view)
        {
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);    
        }