首先自定义一个ViewGroup,可以继承已有的LinearLayout等
public class KeyboardLayout extends LinearLayout {
public KeyboardLayout(Context context) {
super(context);
}
public KeyboardLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public KeyboardLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public KeyboardLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
private int mLayoutHeight = 0;
private int mKeyboardHeight=0;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int h = resolveSize(0, heightMeasureSpec);
mLayoutHeight = Math.max(mLayoutHeight, h); //这里记录原始布局
mKeyboardHeight=Math.max(mKeyboardHeight,Math.abs(mLayoutHeight -h));
if(mKeyboardHeight>mLayoutHeight/5){
存储这个软键盘高度
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
在login页面定义大致如下
核心是KeyboardLayout里面必须有一个ScrollView布局
<LinearLayout>
<KeyboardLayout>
<ScrollView>
<EditText/>
</ScrollView>
</KeyboardLayout>
</LinearLayout>
下面是我的实际代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/default_content_background"
android:orientation="vertical"
tools:context=".modules.login.views.LoginActivity">
<com.maple.subway.modules.login.views.layouts.KeyboardLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="@color/default_font_color" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:lay