I am using the following code to hide the keyboard when a button is clicked:
private OnClickListener saveButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
final View activityRootView = findViewById(R.id.myProfileDetails);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
}
});
//other code that does something
}
}
The button also does some other things but none of it is related to the keyboard and on pressing the button, the activity does not change.
I also have two EditText fields in my activity. When I am using the application and i tap on either field, they gain focus and the keyboard appears. When I press the button, the keyboard disappears and the other code is executed exactly as it should be. In this instance, everything is perfect.
The problem arises when tap on either EditText field for the second time. Now, the EditText gains focus but the keyboard appears and disappears almost instantly without me doing anything. I am guessing my code makes the keyboard disappear permanently after the first time I click the button. Why is this happening and how can I correct this?
you are initializing a
ClickListenerin yourOnClick. which will hide the keyboard as soon asheightDiff>100. Do not do this.do like this