2013-09-22 43 views
1

我想实现一个聊天窗口。也就是说,用户在窗口底部写入,新文本向上滚动现有文本。为此,我创建了一个ScrollViewLinearLayout里面。新的EditText意见被添加到的LinearLayout从底部开始,根据重力布局:聊天窗口ScrollView向下扩展而不是向上

<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允许我向下滚动并将新的空白添加到视图的底部。

只是为了测试方向相反,我改变了线路:

android:gravity="bottom" 
android:layout_gravity="bottom" 

android:gravity="top" 
android:layout_gravity="top" 

同时为滚动型的LinearLayout,并添加新的EditText意见索引0,而不是默认的结尾:

linearLayout.addView(editText, 0); 

而聊天窗口在相反的方向上完美地工作。它可以滚动到输入的第一行。没有什么会丢失。

所以我的问题是什么必须添加到第一种方法来使滚动保持LinearLayout的内容,并不丢失任何文本?

回答

1

好吧,我终于通过查看Android源代码来发现发生了什么。

android:layout_gravity="top"必须设置在LinearLayout

说明:

的儿童定位正在以onLayout()的滚动型计算,正是在父母的onLayout(),在类FrameView。在那里,如果孩子(即LinearLayout)具有底部的layout_gravity,因为它比ScrollView大,则顶部边框在屏幕外部,并且具有负向定位。因此,名单被删除在顶部。 LinearLayout的上边框位置必须为0,并且这可以通过将layout_gravity设置为顶部来实现。