软键盘弹起后将整个内容框顶起:
封装一个类“CustomGlobalLayoutListener”
import android.content.Context; import android.graphics.Rect; import android.view.View; import android.view.ViewTreeObserver.OnGlobalLayoutListener; /** * 实现弹出软键盘时 整个布局向上平移,解决遮挡问题 * 在onCreate中添加监听,在onDestroy中remove监听 * Created by KingsleyCheng on 2017/4/1. */ public class CustomGlobalLayoutListener implements OnGlobalLayoutListener { private Context mContext; private View mRootView; private View mScrollToView; private int btnY; /** * @param context context * @param rootView 可以滚动的布局 * @param scrollToView 界面上被遮挡的位于最底部的布局(控件) */ public CustomGlobalLayoutListener(Context context, View rootView, View scrollToView) { this.mContext = context; this.mRootView = rootView; this.mScrollToView = scrollToView; } @Override public void onGlobalLayout() { Rect rect = new Rect(); // 获取root在窗体的可视区域 mRootView.getWindowVisibleDisplayFrame(rect); int rootViewHeight = mRootView.getRootView().getHeight(); // 当前视图最外层的高度减去现在所看到的视图的最底部的y坐标 int rootInvisibleHeight = rootViewHeight - rect.bottom; //软键盘高度 int heightDifference = rootViewHeight - (rect.bottom - rect.top); // 若rootInvisibleHeight高度大于100,则说明当前视图上移了,说明软键盘弹出了 if (rootInvisibleHeight > 100) { //软键盘弹出来的时候 int[] location = new int[2]; // 获取scrollToView在窗体的坐标 mScrollToView.getLocationInWindow(location); //btnY的初始值为0,一旦赋过一次值就不再变化 if (btnY == 0) { btnY = location[1]; } int scrollToViewHeight = mScrollToView.getHeight(); // 计算root滚动高度,使scrollToView在可见区域的底部 int scrollHeight = (btnY + scrollToViewHeight) - rect.bottom; //如果控件所在的当前高度大于软键盘的高度,控件就不上移 if ((rootViewHeight - location[1] - scrollToViewHeight) < heightDifference) { mRootView.scrollTo(0, scrollHeight); } } else { // 软键盘没有弹出来的时候 mRootView.scrollTo(0, 0); } } }使用方法:
private CustomGlobalLayoutListener customGlobalLayoutListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_create_task); customGlobalLayoutListener = new CustomGlobalLayoutListener(this, scrollView, mBtnNextStep); scrollView.getViewTreeObserver().addOnGlobalLayoutListener (customGlobalLayoutListener); 最后在 onDestroy()生命周期里面取消注册,防止内存溢出 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
- scrollView.getViewTreeObserver().removeOnGlobalLayoutListener(customGlobalLayoutListener);
- } else {
- scrollView.getViewTreeObserver().removeGlobalOnLayoutListener(customGlobalLayoutListener);
- }