Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect dismiss keyboard event in Android

I have a edittext which needs to function like the textfield in iOS. When I click on it, should become editable else it should be disabled. Let's say the user wants to edit a certain value and when he presses the back button, along with the keyboard dismiss I want the edittext to become disabled to edit.

All I am using is the setCursorVisible(true) and setCursorVisible(false) method. I did try using keyCode events but they aren't helping. This is what I have tried up until now:

@Override
    public void onBackPressed() {
// Had the InputMethodManager service here..
        if(imm.isAcceptingText())
        {
           Toast.makeText(ProfileActivity.this,"working",Toast.LENGTH_SHORT).show();
        }
else {
            super.onBackPressed();
            Toast.makeText(ProfileActivity.this,"back pressed called",Toast.LENGTH_SHORT).show();
        }
    }

Also tried overriding keyDown event.

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //replaces the default 'Back' button action
        if(keyCode==KeyEvent.KEYCODE_BACK)
        {

            Log.d("123","called,called");
            return  true;

        }
        return super.onKeyDown(keyCode, event);
    }
like image 422
AndroidMech Avatar asked Apr 20 '15 09:04

AndroidMech


1 Answers

How about creating a subclass of EditText and overriding its onKeyPreIme method

/**
 * This class overrides the onKeyPreIme method to dispatch a key event if the
 * KeyEvent passed to onKeyPreIme has a key code of KeyEvent.KEYCODE_BACK.
 * This allows key event listeners to detect that the soft keyboard was
 * dismissed.
 *
 */
public class ExtendedEditText extends EditText {

    public ExtendedEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }

    public ExtendedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public ExtendedEditText(Context context) {
        super(context);

    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            dispatchKeyEvent(event);
            return false;
        }
        return super.onKeyPreIme(keyCode, event);
    }

}
like image 93
Vrashabh Irde Avatar answered Oct 13 '22 19:10

Vrashabh Irde