只要在BaseActivity加上以下代码
/**
* 要键盘弹出时,scrollView做滑动需,调用此方法
*
* @return
*/
protected void initKeyBoardListener(ScrollView scrollView) {
this.mainScrollView = scrollView;
this.editTexts= new ArrayList<>();
findEditText(scrollView);
setFoucesListener();
}
//当前页面获取了焦点的editText
private ScrollView mainScrollView;
private EditText currentFocusEt;
//当前页面获取了所有的editText
List<EditText> editTexts ;
@Override
protected void onResume() {
super.onResume();
//添加layout大小发生改变监听器
getWindow().getDecorView().addOnLayoutChangeListener(this);
}
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { //获取屏幕高度
int screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
//阀值设置为屏幕高度的1/3
int keyHeight = screenHeight / 3;
//现在认为只要控件将Activity向上推的高度超过了1/3屏幕高,就认为软键盘弹起
if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
Log.e(TAG, "弹起");
if (currentFocusEt != null) {
Log.e(TAG, currentFocusEt.getText().toString());
int[] location = new int[2];
currentFocusEt.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
int height = currentFocusEt.getHeight();
y = y + height;
Log.e(TAG, "bottom:" + bottom + " currentFocusEt.bottom:" + y);
if (y > bottom && mainScrollView != null) {
mainScrollView.scrollBy(0, y - bottom);
}
}
} else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
Log.e(TAG, "收回");
}
}
/**
* 监听焦点获取当前的获取焦点的editText
*
* @param v
* @param hasFocus
*/
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus && v instanceof EditText) {
currentFocusEt = (EditText) v;
}
}
/**
* 找出当前页面的所有editText
*
* @param view
*/
private void findEditText(View view) {
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View v = viewGroup.getChildAt(i);
findEditText(v);
}
} else if (view instanceof EditText) {
editTexts.add((EditText) view);
}
}
/**
* 当前页面的所有editText设置焦点监听
*/
private void setFoucesListener() {
for (EditText et : editTexts) {
et.setOnFocusChangeListener(this);
}
}
在需要处理键盘遮挡输入框的Activity的OnCreate方法里初始化:
调用(Activity里必须有ScrollView ,而且EditText在ScrollView里面)
initKeyBoardListener(findViewById(R.id.scrollview));
另外在AndroidManifest里添加
<activity
android:name=".XXXX"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysHidden|adjustResize" />
喜欢的可以给我扫一下,感谢阅读!