天天看点

Android TextView更新内容后自动滑行到最后一行

原文链接:https://blog.csdn.net/u014341735/article/details/78425437

目前,项目需求中有提到这个,网上找了一些,效果都不理想,不能很好的实现滚动,所以在此将自己实现的方式贴出来,以后或许还会用到!
           
  • 1

实现的两种方式

1.使用TextView实现

通过在XML和代码设置
XML代码如下:
<TextView
   android:id="@+id/txt_showinfo"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:scrollbarStyle="insideOverlay"
   android:fadeScrollbars="false"
   android:scrollbarFadeDuration="2000"/>           
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
代码里进行如下设置:
txt_mmm = (TextView) findViewById(R.id.txt_showinfo);
txt_mmm.setMovementMethod(ScrollingMovementMethod.getInstance());

txt_mmm.post(new Runnable() {
    @Override
    public void run() {
        txt_mmm.append(showString);
        int scrollAmount = txt_mmm.getLayout().getLineTop(txt_mmm.getLineCount()) 
           - txt_mmm.getHeight();
        if (scrollAmount > )
            txt_mmm.scrollTo(, scrollAmount);
         else
            txt_mmm.scrollTo(, );                 
    }
});           
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

2.使用ScrollView和TextView共同实现

通过在XML和代码设置
XML代码如下:
<ScrollView
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true">   
    <TextView
        android:id="@+id/txt_info"
        android:scrollbars="vertical"
        android:scrollbarStyle="insideOverlay"
        android:fadeScrollbars="false"
        android:scrollbarFadeDuration="2000"
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </TextView>
</ScrollView>           
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
代码里进行如下设置:
scrollView = (ScrollView) findViewById(R.id.scrollview);
txt_info = (TextView) findViewById(R.id.txt_info);
txt_info.setMovementMethod(ScrollingMovementMethod.getInstance());

txt_info.append(showString);
scrollView.post(new Runnable() {
    @Override
    public void run() {
        scrollView.smoothScrollTo(, txt_info.getBottom());
    }
});           
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
注意:两种方式虽能实现这个效果,但具体还是有些许差异,待后续测试完毕再给出结论。

参考地址:http://ask.csdn.net/questions/107/