public class ScrollRelativeLayout extends RelativeLayout {
private Scroller mScroller;
private View mAnchor;
private static final String TAG = "ScrollRelativeLayout";
private List<EditText> mChildEtList = new ArrayList<>();
private boolean isFirst = true;
private EditText focusET;
public ScrollRelativeLayout(Context context) {
super(context);
init();
}
public ScrollRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ScrollRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setAnchor(View anchor) {
this.mAnchor = anchor;
}
private void init() {
mScroller = new Scroller(getContext());
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (mAnchor == null) return;
if (isFirst) {
isFirst = false;
//遍历并保存所有editText并设置焦点改变监听
collectChild(ScrollRelativeLayout.this);
}
Rect rect = new Rect();
getWindowVisibleDisplayFrame(rect);
int mainInvisibleHeight = getRootView().getHeight() - rect.bottom;
if (mainInvisibleHeight > 400) {
int[] location = new int[2];
mAnchor.getLocationInWindow(location);
//计算系统由于键盘遮挡editText导致布局移动的距离
int delta = mainInvisibleHeight - DensityUtil.getScreenHeight(getContext()) + getFocusViewY();
if (delta <= 0) {
delta = 0;
}
int scrollHeight = (location[1] + mAnchor.getHeight()) - rect.bottom - delta;
if (scrollHeight < 0) {
return;
}
mScroller.startScroll(getScrollX(), getScrollY(), 0, scrollHeight, 500);
invalidate();
// scrollBy(0 , scrollHeight);
} else {
int scrollY = getScrollY();
if (scrollY <= 0) {
return;
}
mScroller.startScroll(getScrollX(), scrollY, 0, -scrollY, 500);
invalidate();
// scrollTo(0 , 0);
}
}
});
}
private void collectChild(ViewGroup parent) {
int count = parent.getChildCount();
for (int i = 0; i < count; i++) {
View view = parent.getChildAt(i);
if (view instanceof ViewGroup) {
collectChild((ViewGroup) view);
} else if (view instanceof EditText) {
EditText et = (EditText) view;
et.setOnFocusChangeListener(listener);
mChildEtList.add(et);
}
}
}
private OnFocusChangeListener listener = new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus && v instanceof EditText)
focusET = (EditText) v;
}
};
private int getFocusViewY() {
if (focusET != null) {
int[] location = new int[2];
focusET.getLocationInWindow(location);
return location[1] + focusET.getHeight();
}
return 0;
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
postInvalidate();
} else {
// LogUtils.d(TAG , "scrollY = " + getScrollY());
}
}
}
登录页面如果输入框在下面,键盘弹出的时候会把输入框遮挡住
解决方法:把这个view设置为根布局,使用时把btn设置为锚点就好了
mView.setAnchor(btn)