Android 软键盘的监听(监听高度,是否显示)

来源:互联网 发布:淘宝虚拟试衣间关了吧 编辑:程序博客网 时间:2024/06/05 14:13
  1. 转自:http://blog.csdn.net/daguaio_o/article/details/47127993

  2. Android官方本身没有提供一共好的方法来对软键盘进行监听,但我们实际应用时,很多地方都需要针对软键盘来对UI进行一些优化。

    以下是整理出来的一个不错的方法,大家可以使用。


  3. public class SoftKeyboardUtil {  
  4.     public static void observeSoftKeyboard(Activity activity, final OnSoftKeyboardChangeListener listener) {  
  5.         final View decorView = activity.getWindow().getDecorView();  
  6.         decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {  
  7.             int previousKeyboardHeight = -1;  
  8.             @Override  
  9.             public void onGlobalLayout() {  
  10.                 Rect rect = new Rect();  
  11.                 decorView.getWindowVisibleDisplayFrame(rect);  
  12.                 int displayHeight = rect.bottom - rect.top;  
  13.                 int height = decorView.getHeight();  
  14.                 int keyboardHeight = height - displayHeight;  
  15.                 if (previousKeyboardHeight != keyboardHeight) {  
  16.                     boolean hide = (double) displayHeight / height > 0.8;  
  17.                     listener.onSoftKeyBoardChange(keyboardHeight, !hide);  
  18.                 }  
  19.   
  20.                 previousKeyboardHeight = height;  
  21.   
  22.             }  
  23.         });  
  24.     }  
  25.   
  26.     public interface OnSoftKeyboardChangeListener {  
  27.         void onSoftKeyBoardChange(int softKeybardHeight, boolean visible);  
  28.     }  
0 0