输入时键盘弹出,布局整体上移

先上效果图

关键代码:
1.在AndroidManifest.xml设置对应的Activity:
android:windowSoftInputMode="adjustResize"
2.activity对应的布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:clipToPadding="false"
android:fitsSystemWindows="true">

<ScrollView
android:id="@+id/sv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:fillViewport="true"
android:scrollbars="none">

<RelativeLayout
android:id="@+id/sv_content_rl"
android:layout_width="match_parent"
android:layout_height="wrap_content">
....
</RelativeLayout>

</ScrollView>

<ImageView
android:id="@+id/login_close_iv"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_marginLeft="17.5dp"
android:layout_marginTop="17.5dp"
android:background="@mipmap/w_back_title_click" />
//注册帐号
</RelativeLayout>

3.activity代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
root = (RelativeLayout) findViewById(R.id.root_rl);
//键盘显示,触摸键盘以外隐藏键盘
findViewById(R.id.sv_content_rl).setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
// imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
return false;
}
});
root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
View focus = root.findFocus();
ScrollView sv = ((ScrollView) findViewById(R.id.sv));
sv.fullScroll(ScrollView.FOCUS_DOWN);

if (focus != null && focus instanceof EditText) {//保证滑动之后 焦点依然未变
focus.requestFocus();
}

int loc[] = new int[2];
View view = findViewById(R.id.regist_area);
view.getLocationOnScreen(loc);
if (getScreenHeight(MainActivity.this) - loc[1] < Math.abs(getScreenHeight(MainActivity.this) / 2 - loc[1])) {//无压缩状态
view.setVisibility(View.VISIBLE);
} else {
view.setVisibility(View.INVISIBLE);
}
}
});

附上源码:https://github.com/Waychel/LayoutAboveKeyBoard

另外,还可以自定义Layout通过onLayout()方法来实现、或可以在Activity内嵌DialogFragment,先记下,有空再写。