ScrollView总是滚动到底部

14

我在我的布局中定义了一个带有文本编辑框的ScrollView:

 <ScrollView android:fillViewport="true"
     android:layout_marginBottom="50dip"
     android:id="@+id/start_scroller"
     android:layout_height="fill_parent"
     android:layout_width="fill_parent"
     android:fadingEdge="none">
 <TextView  
    android:id="@+id/text"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" >
 </TextView>
 </ScrollView>

我使用以下方法向这个ScrollView添加文本:

public void writeToLogView(String textMsg) {
   if (text.getText().equals("")) {
       text.append(textMsg);
   } else {
    text.append("\n" + textMsg);
    scroller.scrollBy(0, 1000000);
   }
}

你可以看到,我追加了文本并尝试滚动到ScrollView的底部。不幸的是,这并没有正常工作。它会向下滚动,但并不总是滚动到底部。有什么提示吗?

3个回答

30

或者在scrollView视图大小更改后使用:

scroller.post(new Runnable() { 
    public void run() { 
        scroller.fullScroll(ScrollView.FOCUS_DOWN); 
    } 
}); 

2
这对我也起作用了,但是我使用了postDelayed(),延迟很低,例如20毫秒。 - Snailer
太好了,谢谢提示!我之前一直在使用 scrollTo(0,0),但它似乎没有起到作用。 - Bostone

7

在追加文本后,尝试使用您的TextView的尺寸来计算应该滚动到哪里,而不是一些常数,像这样:

scroller.post(new Runnable() {

    public void run() {
        scroller.scrollTo(text.getMeasuredWidth(), text.getMeasuredHeight());
    }
});

0

对于那些正在使用Android Annotations的人,你可以像这样做:

@ViewById
ScrollView myScrollView;

@AfterViews
protected void init() {
    scrollToEnd();
}

@UiThread(delay=200)
void scrollToEnd() {
    myScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接