2013-02-07 55 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); 
    } 
});