说在前面的话
虽然网上的教程已经很多了,但是这里博主还是要写,就当众多教程中的一篇吧~
实现思路
众所周知,在oncreate中View.getWidth和View.getHeight获得的view的高度和宽度为0,这是因为View组件布局要在onResume回调后完成。所以我们这里为rootView(根布局)添加一个OnGlobalLayoutListener监听。查看这个监听器的源码我们可以知道,当view发生改变的时候可以回调。
public interface OnGlobalLayoutListener {
/**
* Callback method to be invoked when the global layout state or the visibility of views
* within the view tree changes
*/
public void onGlobalLayout();
}
这里我们去监听rootView的可见区域,因为当软键盘弹出来之后,rootView的可见区域会发生变化。监听到之后,我们把rootView上移就行了。(rootView.getViewTreeObserver().addOnGlobalLayoutListener)
那么我们怎么去监听可见区域的变化呢?看下面,我们只要在监听器的回调中做处理即可
Rect rect = new Rect();