欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中监听软键盘显示状态实现代码

程序员文章站 2022-03-23 13:54:38
/**监听软键盘状态 * @param activity * @param listener */ public static voi...
/**监听软键盘状态
   * @param activity
   * @param listener
   */
  public static void addonsoftkeyboardvisiblelistener(activity activity, final onsoftkeyboardvisiblelistener listener) {
    final view decorview = activity.getwindow().getdecorview();
    decorview.getviewtreeobserver().addongloballayoutlistener(new viewtreeobserver.ongloballayoutlistener() {
      @override
      public void ongloballayout() {
        rect rect = new rect();
        decorview.getwindowvisibledisplayframe(rect);
        int displayhight = rect.bottom - rect.top;
        int hight = decorview.getheight();
        boolean visible = (double) displayhight / hight < 0.8;
         
        log.d(tag, "decorview display hight = " + displayhight);
        log.d(tag, "decorview hight = " + hight);
        log.d(tag, "softkeyboard visible = " + visible);
 
        if(visible != slastvisiable){
          listener.onsoftkeyboardvisible(visible);
        }
        slastvisiable = visible;
      }
    });
  }