How do I know if the keyboard is visible?

0

Is there a method that tells me when the keyboard appears and disappears?

    
asked by anonymous 12.02.2014 / 00:31

2 answers

2

There is no direct method to achieve this. What we can do is check if the height of our layout has changed.

For this, declare a method that will be executed when our Layout has its state or visibility changed.

final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
        if (heightDiff > 100) { // Se são mais de 100 pixels, provávelmente é o keyboard...
            //... faça aqui o que quer quando o teclado passa a ser visível.
        }
     }
});  

Notes

  

1 - This code should be placed in the onCreate method of our Activity .   2 - The Layout root of Activity must have a Id assigned so that it can be referenced in the code, in this case it is activityRoot .   3 - You should add this attribute to your Activity : android:windowSoftInputMode="adjustResize"

Adapted from this answer from SO.com

    
12.02.2014 / 15:27
1

Try this:

InputMethodManager imm = (InputMethodManager) getActivity()
            .getSystemService(Context.INPUT_METHOD_SERVICE);

    if (imm.isAcceptingText()) {
        writeToLog("Visível");
    } else {
        writeToLog("Não visível");
    }

More details here .

    
12.02.2014 / 03:01