2011-03-07 139 views
20

我有一個包含Android應用中的文本視圖的滾動視圖。該文本視圖將以設定的時間間隔連續添加文本。滾動工作和文本添加得很好,但我想要做的是滾動視圖自動向下滾動,因爲文本被添加。隨着新文本被添加到底部,它會自動向下滾動以匹配,並且舊文本被排除在頂部。更好的辦法是在滾動視圖的底部添加文本,並讓它向上推動舊文本,但一次只能推送一個文本。添加了文本的Android滾動視圖自動滾動

+2

那麼......無視這一點。傻傻的我沒有把重力設置在textview(而不是scrollview)上的「底部」。這樣做會將新文本保留在底部並滾動以符合新文本。好極了! – AndroidHopeful 2011-03-07 20:32:28

+3

您可以在答案中寫下您的解決方案,然後將其標記爲已選。當其他人遇到同樣的問題時,他們會看到有解決方案。 – Shade 2011-03-08 00:10:35

+2

這是一個很酷的解決方案,你應該把它作爲答案。 – 2011-06-09 13:50:22

回答

20
<ScrollView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:fillViewport="true" 
    > 
    <TextView 
     android:id="@+id/statusText" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="bottom" /> 
</ScrollView> 
+0

謝謝,這對我有用。 – BostonGeorge 2013-12-16 01:16:14

2

添加文本時,您可以將整個ScrollView滾動到底部。

textView.append(text); 
scroll.fullScroll(View.FOCUS_DOWN) 
+0

不要忘了打電話給fullScroll裏面scroll.post電話 – 2014-07-18 15:48:51

1
textView.append(text); 
scroll.fullScroll(View.FOCUS_DOWN) 

這會給問題,它不會滾動高達極端的頂部,由於android:layout_gravity="bottom"

+0

輝煌的解決方案,謝謝 – 2014-08-19 12:35:42

+0

這應該被標記爲答案。 – busuu 2017-03-03 02:32:42

6

我試着重力解決方案,但結果是在實際文本有很多空的空間當滾動到底部。

所以這是另一種方式。您可以將您的TextView滾動型的內部:

<ScrollView 
    android:id="@+id/scrollView1" 
    android:layout_width="match_parent" 
    android:layout_height="0dp" 
    android:layout_weight="1" 
    android:fillViewport="true" > 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

</ScrollView> 

,並定義addTextChangedListener

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

      //some code here 

     ScrollView scrollView1 = (ScrollView) findViewById(R.id.scrollView1); 
     TextView textView1 = (TextView) findViewById(R.id.textView1); 
     textView1.addTextChangedListener(new TextWatcher() { 

     @Override 
     public void afterTextChanged(Editable arg0) { 
      scrollView1.fullScroll(ScrollView.FOCUS_DOWN); 
      // you can add a toast or whatever you want here 
     } 

     @Override 
     public void beforeTextChanged(CharSequence arg0, int arg1, 
       int arg2, int arg3) { 
      //override stub 
     } 

     @Override 
     public void onTextChanged(CharSequence arg0, int arg1, int arg2, 
       int arg3) { 
      //override stub 
     } 

    }) } 

其實我注意到現在應用程序將每滾動文本改變時,不只是增加。然而,它對我來說工作得很好。

+0

這是唯一適合我的(API 23)。 'android:layout_gravity =「bottom」'技巧讓我無法手動向上滾動,並在文本下方添加了大量空白空間。這一個沒有添加空的空間,並允許正常滾動。 – Shlublu 2016-11-14 16:15:14