我刚刚在装有 Android 7.1.1 和 Android 支持库 25.3.1 的 Nexus 9 上观察到以下行为。
这是我的 Activity 布局:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:orientation="vertical"
android:paddingBottom="4dp">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<View
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#fffaaa" />
<View
android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#bbbaaa" />
<View
android:layout_width="match_parent"
android:layout_height="10dp"
android:background="#f00" />
</LinearLayout>
</ScrollView>
这是它在屏幕上的样子:
当屏幕键盘出现时,系统会调整我的 Activity 布局的大小,以便它占据从屏幕顶部到键盘的空间。请考虑以下屏幕截图中的红色虚线:
但是,当我用 NestedScrollView
替换 ScrollView
时,系统不会调整布局大小:
现在红色虚线位于键盘下方。通过对 Activity 应用 android:windowSoftInputMode="adjustResize"
可以轻松解决此问题:
红色虚线现在位于键盘上方。我的问题是:
- 为什么我会观察到这种行为?
NestedScrollView
有什么问题?
最佳答案
Android docs说:
When the input method appears on the screen, it reduces the amount of space available for your app's UI. The system makes a decision as to how it should adjust the visible portion of your UI, but it might not get it right. To ensure the best behavior for your app, you should specify how you'd like the system to display your UI in the remaining space.
这可能是所引用的不稳定性的一个实例。
在我看来,这不是 NestedScrollView
和 ScrollView
的问题,而是 Activity 如何根据键盘调整 UI 的问题. NestedScrollView
和 ScrollView
之间的唯一区别是 NestedScrollView
能够既是父 又是 child. 我认为这强调了为什么你应该遵循上面的建议:
To ensure the best behavior for your app, you should specify how you'd like the system to display your UI in the remaining space.
即始终使用 android:windowSoftInputMode="adjustResize"
,而不是仅在需要时使用。
关于当层次结构中有 NestedScrollView 时,Android 不会调整我的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43455321/