1.键盘弹出时屏幕可以滑动
在布局里面添加
android:fitsSystemWindows="true"
2.键盘弹出时把所有内容顶上去
(1).首先一个工具类:
public class KeyboardLayout extends FrameLayout {
private KeyboardLayoutListener mListener;
private boolean mIsKeyboardActive = false; //输入法是否激活
private int mKeyboardHeight = 0; // 输入法高度
public KeyboardLayout(Context context) {
this(context, null, 0);
}
public KeyboardLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public KeyboardLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// 监听布局变化
getViewTreeObserver().addOnGlobalLayoutListener(new KeyboardOnGlobalChangeListener());
}
public void setKeyboardListener(KeyboardLayoutListener listener) {
mListener = listener;
}
public KeyboardLayoutListener getKeyboardListener() {
return mListener;
}
public boolean isKeyboardActive() {
return mIsKeyboardActive;
}
/**
* 获取输入法高度
*
* @return
*/
public int getKeyboardHeight() {
return mKeyboardHeight;
}
public interface KeyboardLayoutListener {
/**
* @param isActive 输入法是否激活
* @param keyboardHeight 输入法面板高度
*/
void onKeyboardStateChanged(boolean isActive, int keyboardHeight);
}
private class KeyboardOnGlobalChangeListener implements ViewTreeObserver.OnGlobalLayoutListener {
int mScreenHeight = 0;
private int getScreenHeight() {
if (mScreenHeight > 0) {
return mScreenHeight;
}
mScreenHeight = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay().getHeight();
return mScreenHeight;
}
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
// 获取当前页面窗口的显示范围
((Activity) getContext()).getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
int screenHeight = getScreenHeight();
int keyboardHeight = screenHeight - rect.bottom; // 输入法的高度
boolean isActive = false;
if (Math.abs(keyboardHeight) > screenHeight / 4) {
isActive = true; // 超过屏幕五分之一则表示弹出了输入法
mKeyboardHeight = keyboardHeight;
}
mIsKeyboardActive = isActive;
if (mListener != null) {
mListener.onKeyboardStateChanged(isActive, keyboardHeight);
}
}
}
}
(2).在布局最外层引用这个控件,并设置id
<com.lmc.cityrabbit.utils.KeyboardLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/keyboard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".view.activity.ContractContentActivity">
(3).清单文件对应Activity添加
<activity android:name=".view.activity.RentActivity"
android:windowSoftInputMode="adjustResize"
/>
(4).Activity里面
keyboard.setKeyboardListener((isActive, keyboardHeight) -> {
if (isActive) {
scrollToBottom();
}
});
private void scrollToBottom() {
scroll.postDelayed(new Runnable() {
@Override
public void run() {
scroll.smoothScrollTo(0, scroll.getBottom());
}
}, 100);
}
3.最外层布局使用ScrollView(还未尝试此方法)