我怎么知道键盘是开放的

Ash*_*ava 6 android

我怎么才能知道键盘是否打开.实际上我的问题是,如果键盘打开,那么我只是要求隐藏,而不是总是调用hide.有什么方法可以检查键盘是否打开?目前我正在使用这种方法来隐藏键盘.

EditText myEditText = (EditText) findViewById(R.id.myEditText);
View view = this.getCurrentFocus();
if (view != null) {ditText) findViewById(R.id.myEditText);
View view = this.getCurrentFocus();
if (view != null) { Inp` 
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
Run Code Online (Sandbox Code Playgroud)

Adi*_*ikh 1

尝试 GlobalLayout Listener,例如:

    main_layout.getViewTreeObserver().addOnGlobalLayoutListener(
        new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() 
                {

                    Rect r = new Rect();
                    // r will be populated with the coordinates of your view
                    // that area still visible.
                    main_layout.getWindowVisibleDisplayFrame(r);

                    int heightDiff = main_layout.getRootView().getHeight()-(r.bottom -r.top);    
                   //if(hightDiff>100) --> It may be keyboard.

                }
});
Run Code Online (Sandbox Code Playgroud)

将 main_layout 替换为您的布局。

  • 为什么你要复制并粘贴答案?你可以只发布答案链接 (2认同)
  • 我没有引用您的评论和链接...我以前在我的应用程序中使用过此代码,所以我将其从那里放在这里。 (2认同)