2013-03-04 49 views
2

我试图赶上从屏幕移除键盘的情况下,我用下面的代码:Android。如何捕捉键盘被隐藏的时刻?

searchTextField.setOnEditorActionListener(new OnEditorActionListener() 
    { 
     public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
     { 

      System.out.println("ACTION ID " + actionId); 

      if(actionId == EditorInfo.IME_ACTION_DONE) 
      { 
       System.out.println("ACTION DONE!!!!!!!!!!"); 
       return true; 
      } 

      return false; 
     } 

    searchTextField.setOnFocusChangeListener(new View.OnFocusChangeListener() 
    { 
     public void onFocusChange(View v, boolean hasFocus) 
     { 
       if (hasFocus) 
        System.out.println("HAS FOCUS"); 
       else 
        System.out.println("FOCUS LOST"); 
     } 
    }); 

不过遗憾的是它不工作。 onEditorAction只是从来没有叫过,不管我是否开始编辑或完成。关于onFocusChange方法,它只是在键盘上升时第一次调用。当键盘关闭或第二次升起时,它不会被调用。任何人都可以解释我做错了什么?

+0

[Android系统可能重复。 onEditorAction从来没有叫过](http://stackoverflow.com/questions/15202771/android-oneditoraction-never-called) – Luksprog 2013-03-04 14:30:29

回答

1

我用GlobalLayoutListener上的活动rootView用于检查键盘是否被隐藏或可见:

其工作原理如下:

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) { // if more than 100 pixels, its probably a keyboard... 
       ... do something here 
      } 
     } 
    }); 
+0

赫......谢谢你,伙计,但我不能得到你的答案如何与我的问题? – 2013-03-04 14:36:58

+0

使用我粘贴的代码哟得到键盘被隐藏或键盘是可见的事件。 – 2013-03-04 14:38:52

+0

使用这个,你将收到一个事件,如果用户试图隐藏键盘 – 2013-03-04 14:39:56