如何验证虚拟键盘可见性?

时间:2016-04-25 09:47:09

标签: android

我想在虚拟键盘打开时显示一个按钮,如果虚拟键盘可见性关闭则隐藏此按钮。但是我找不到任何侦听器来执行此活动。 有谁知道怎么做?

3 个答案:

答案 0 :(得分:0)

如找到here,您需要实例化SoftkeyBoard并添加一个监听器。

/*
Somewhere else in your code
*/

RelativeLayout mainLayout = findViewById(R.layout.main_layout); // You must use your root layout
InputMethodManager im = (InputMethodManager) getSystemService(Service.INPUT_METHOD_SERVICE);     

/*
Instantiate and pass a callback
*/

SoftKeyboard softKeyboard;
softKeyboard = new SoftKeyboard(mainLayout, im);
softKeyboard.setSoftKeyboardCallback(new SoftKeyboard.SoftKeyboardChanged()
{
 @Override  
  public void onSoftKeyboardHide()   
  {
        // Code here  
  }  

  @Override 
   public void onSoftKeyboardShow()  
   { 
       // Code here 
   }   
});     

/*
Open or close the soft keyboard programatically
*/

softKeyboard.openSoftKeyboard();
softKeyboard.closeSoftKeyboard();


/*
SoftKeyboard can catch keyboard events when an EditText gains focus and keyboard appears
*/


/* Prevent memory leaks:
*/

@Override
public void onDestroy()
{  
  super.onDestroy(); 
   softKeyboard.unRegisterSoftKeyboardCallback();
}

在他的帖子中,您还可以找到有关错误修复和可能出现问题的更多信息。

答案 1 :(得分:0)

将onGlobalLayoutListener添加到您的活动/片段的父视图中,并相应地使您的按钮可见

final View parentView= findViewById(R.id.myrootview);  
       parentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int heightDiff = root.getRootView().getHeight() - root.getHeight();

            Rect rectgle= new Rect();
            Window window= getWindow();
            window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
            int contentViewTop= 
                window.findViewById(Window.ID_ANDROID_CONTENT).getTop();

            if(heightDiff <= contentViewTop){
                //Soft KeyBoard Hidden---button visible

            }else{
                //Soft KeyBoard Shown---button hide
            }


         }
    });

答案 2 :(得分:0)

键盘打开和关闭没有直接事件。但您可以在完整布局上创建观察者,然后显示按钮或您想要做的任何事情。 对于Observer代码,请检查此项 - Hide part of activity_main.xml if keyboard is open (Android)