我想实现一个聊天窗口。也就是说,用户在窗口底部书写,新文本向上滚动现有文本。为此,我创建了一个 ScrollView,其中包含一个 LinearLayout。根据引力布局,新的 EditText View 从底部开始添加到 LinearLayout:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:layout_gravity="bottom"
android:fillViewport="true"
tools:context=".Chat">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="bottom"
android:layout_gravity="bottom"
android:layout_alignParentBottom="true"/>
</ScrollView>
这很好用,但是当我想看到屏幕上方的“隐藏文本”并且我向上滚动它时,我已经在滚动的末尾并且隐藏文本有消失了。相反,ScrollView 允许我向下滚动并在 View 底部添加了新的空白区域。
只是为了测试相反的方向,我更改了行:
android:gravity="bottom"
android:layout_gravity="bottom"
到
android:gravity="top"
android:layout_gravity="top"
对于 ScrollView 和 LinearLayout,还添加索引为 0 的新 EditText View ,而不是最后的默认值:
linearLayout.addView(editText, 0);
聊天窗口在相反的方向上从上到下运行得非常好。它可以向下滚动到输入的第一行。什么都没有丢失。
所以我的问题是第一种方法必须添加什么才能使滚动保留 LinearLayout 的内容并且不会丢失任何文本?
最佳答案
好吧,我终于通过查看 Android 源代码发现了发生了什么。
android:layout_gravity="top"
必须在 LinearLayout 中设置。
解释:
子定位在 ScrollView 的 onLayout() 中计算,恰好在类 FrameView 中父级的 onLayout() 中。那里,如果 child (也就是LinearLayout)有一个底部的layout_gravity,因为它比ScrollView大,所以顶部边框在屏幕外,负定位。因此,该列表在顶部被剪切。 LinearLayout 的顶部边框位置必须为 0,这是通过将 layout_gravity 设置为顶部来实现的。
关于android - 聊天窗口 ScrollView 向下展开而不是向上展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18944052/