Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to detect Android Softkeyboard

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.48k
    Comment on it

    When user hits the BACK-Button on his android device, the keyboard disappears. How can I catch that event? In order to track softkeyboard is open or not, this tutorial is helpfull for you, and you will easily dissmiss the softkeyboard by pressing back button.

    Create a class BackAwareEdittext that extends the EditText, just override the method onKeyPreIme to catch the KEYCODE_BACK event and ACTION_UP event.

    private BackPressedListener mOnImeBack;
    
    public BackAwareEdittext(Context context) {
        super(context);
    }
    
    public BackAwareEdittext(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public BackAwareEdittext(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    
    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP){
            if (mOnImeBack != null) mOnImeBack.onImeBack(this);
        }
        return super.dispatchKeyEvent(event);
    }
    
    public void setBackPressedListener(BackPressedListener listener) {
        mOnImeBack = listener;
    }
    
    public interface BackPressedListener {
        void onImeBack(BackAwareEdittext etWrite);
    }
    

    MainActivity.java

    When user selects the EditText softkeyboard appear, and setBackPressedListener will dismisses the keyboard by pressing the BACK key.

     BackAwareEdittext etWrite=(BackAwareEdittext)findViewById(R.id.etWrite);
    
        etWrite.setBackPressedListener(new BackAwareEdittext.BackPressedListener() {
               @Override
               public void onImeBack(BackAwareEdittext etWrite) {
                   isKeyboardOpen=false;
                       Toast.makeText(MainActivity.this,"Keyboard close",Toast.LENGTH_SHORT).show();
               }
           });
    
           etWrite.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   isKeyboardOpen=true;
                   Toast.makeText(MainActivity.this,"Keyboard open",Toast.LENGTH_SHORT).show();
               }
           });
    

    Make android:windowSoftInputMode="stateHidden" in **AndroidManifest.xml** to make sure that keyboard is closed(by default).

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: