How do I detect if software keyboard is visible on Android Device or not?

前端 未结 30 1872
情书的邮戳
情书的邮戳 2020-11-22 10:59

Is there a way in Android to detect if the software (a.k.a. \"soft\") keyboard is visible on screen?

30条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 11:34

    final View activityRootView = findViewById(R.id.rootlayout);
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
    
                Rect r = new Rect();
                activityRootView.getWindowVisibleDisplayFrame(r);
    
                int screenHeight = activityRootView.getRootView().getHeight();
                Log.e("screenHeight", String.valueOf(screenHeight));
                int heightDiff = screenHeight - (r.bottom - r.top);
                Log.e("heightDiff", String.valueOf(heightDiff));
                boolean visible = heightDiff > screenHeight / 3;
                Log.e("visible", String.valueOf(visible));
                if (visible) {
                    Toast.makeText(LabRegister.this, "I am here 1", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LabRegister.this, "I am here 2", Toast.LENGTH_SHORT).show();
                }
            }
    });
    

提交回复
热议问题