The ways to manage Android software keyboard visibility have already discussed so much on web.
But some of old solutions on web does not work since the view hierarchy of Activity changes over time.
Therefore, the following solution may not work in the future.
public class KeyboardHelper {
public interface KeyboardListener {
void onShowKeyboard();
void onHideKeyboard();
}
public static ViewTreeObserver.OnGlobalLayoutListener setKeyboardListener(
@NonNull View rootChildView, @NonNull KeyboardListener listener) {
return () -> {
int bottomPadding = rootChildView.getPaddingBottom();
if (bottomPadding > 0) {
listener.onShowKeyboard();
} else {
listener.onHideKeyboard();
}
};
}
}
Add the following code in onCreate of your activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
ViewGroup rootView = (ViewGroup) mYourLayoutRootView.getRootView();
View rootChildView = rootView.getChildAt(0);
mKeyboardLayoutListener = KeyboardHelper.setKeyboardListener(rootChildView, this);
mYourLayoutRootView.getViewTreeObserver().addOnGlobalLayoutListener(mKeyboardLayoutListener);
}
Also, implement KeyboardListener.
@Override
public void onShowKeyboard() {
// some code
}
@Override
public void onHideKeyboard() {
// some code
}
And do not forget to remove ViewTreeObserver.OnGlobalLayoutListener.
@Override
protected void onDestroy() {
mYourLayoutRootView.getViewTreeObserver().removeOnGlobalLayoutListener(mKeyboardLayoutListener);
super.onDestroy();
}
Please note that onShowKeyboard and onHideKeyboard methods are called multiple times.
If you want to avoid its behaviour, define flag to control it.