android监听虚拟键盘隐藏和显示事件

刚开始在onconfigurationChanged中监听,结果发现该方法在configuration变化即配置文件发生变化时才会被调用,如横竖屏切换,android重新载入配置文件时。而键盘隐藏不会触发该方法。

后来采用如下方法完美解决了键盘隐藏监听事件。

//该Activity的最外层Layout

finalView activityRootView = findViewById(R.id.activityRoot);

//给该layout设置监听,监听其布局发生变化事件
activityRootView
.getViewTreeObserver().addOnGlobalLayoutListener(newOnGlobalLayoutListener(){


   
@Override
   
publicvoid onGlobalLayout(){

       //比较Activity根布局与当前布局的大小
       
int heightDiff = activityRootView.getRootView().getHeight()- activityRootView.getHeight();
       
if(heightDiff >100){

        //大小超过100时,一般为显示虚拟键盘事件

             }else{

        //大小小于100时,为不显示虚拟键盘或虚拟键盘隐藏

       }
    
}
});

猜你喜欢

转载自hunankeda110.iteye.com/blog/1856143
今日推荐