2013-09-22 49 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設置爲頂部來實現。