2013-02-07 56 views
0

我正在構建一個類似聊天的應用程序,用於顯示用戶使用滾動視圖輸入到屏幕的文本。我想要做的是隨着更多的文本被添加到屏幕上,使滾動視圖自動滾動。 我正在使用textview來顯示輸入。 scrollview的xml部分如下:android中的自動滾動textview

<ScrollView 
     android:id="@+id/scroller" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_above="@id/buttons"  
     > 

<LinearLayout 
    android:id="@+id/start_chat" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    > 

</LinearLayout> 

</ScrollView> 

我該如何去做這件事?我嘗試將佈局的引力設置爲「底部」,但這不能正常工作(隨着滾動視圖向下滾動而向上移動的文本無法再被查看)。

任何幫助,非常感謝。

+0

你可以做到這一點,以及從'webview'和JavaScript添加了一個新的聊天了! :) – sadaf2605

回答

1

如果您想滾動到絕對底部(添加新TextView的位置),則在添加TextView時,在ScrollView上使用fullScroll

ScrollView my_scrollview = (ScrollView) findViewById(R.id.scroller); 
my_scrollview.fullScroll(ScrollView.FOCUS_DOWN); 

相反,如果你想從滾動當前位置的用戶正在查看相對的,我會嘗試像smoothScrollByscrollBy

/* recently_added_textview being the TextView that was added to trigger this */ 
ScrollView my_scrollview = (ScrollView) findViewById(R.id.scroller); 
int height = recently_added_textview.getHeight(); 
my_scrollview.smoothScrollBy(0, height); 
/* x being 0 assuming you don't want to scroll left and right */ 

這樣,用戶就不會被髮送到底部ScrollView如果他們正在讀頂部或中間的東西。

+0

這似乎工作,雖然由於某種原因,因爲鍵盤通常在聊天時在屏幕上,當滾動視圖向下滾動它不完全 - 最新的textview添加不顯示。我該如何解決這個問題? – Malfunction

+0

@Malfunction你確定它是在添加TextView之後滾動而不是之前?如果是這樣,請嘗試Ramyle的答案。 – Samutz

0

您可以添加此你在TextView的

scroller.post(new Runnable() { 
    public void run() { 
     //ScrollView.FOCUS_DOWN if you want to scroll down 
     //ScrollView.FOCUS_UP if you want to scroll up 
     svComments.fullScroll(ScrollView.FOCUS_DOWN); 
    } 
});