Androidデバイスでソフトウェアキーボードが表示されているかどうかをどのように検出しますか? 質問する

Androidデバイスでソフトウェアキーボードが表示されているかどうかをどのように検出しますか? 質問する

Android で、ソフトウェア (別名「ソフト」) キーボードが画面に表示されているかどうかを検出する方法はありますか?

ベストアンサー1

これは私にとってはうまくいきました。おそらく、これはすべてのバージョンで常に最善の方法です。

onGlobalLayout メソッドが何度も呼び出されるため、キーボードの可視性のプロパティを作成して、この変更が遅れて発生するのを観察することが効果的です。また、デバイスの回転をチェックして、windowSoftInputModeそうでないかを確認するのも良いでしょうadjustNothing

boolean isKeyboardShowing = false;
void onKeyboardVisibilityChanged(boolean opened) {
    print("keyboard " + opened);
}

// ContentView is the root view of the layout of this activity/fragment    
contentView.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        Rect r = new Rect();
        contentView.getWindowVisibleDisplayFrame(r);
        int screenHeight = contentView.getRootView().getHeight();

        // r.bottom is the position above soft keypad or device button.
        // if keypad is shown, the r.bottom is smaller than that before.
        int keypadHeight = screenHeight - r.bottom;

        Log.d(TAG, "keypadHeight = " + keypadHeight);

        if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
            // keyboard is opened
            if (!isKeyboardShowing) {
                isKeyboardShowing = true;
                onKeyboardVisibilityChanged(true);
            }
        }
        else {
            // keyboard is closed
            if (isKeyboardShowing) {
                isKeyboardShowing = false;
                onKeyboardVisibilityChanged(false);
            }
        }
    }
});

おすすめ記事