TextView更新文本时自动滑动到最后一行
版权声明:本文为博主原创文章,允许转载,但请保留出处。
目前,项目需求中有提到这个,网上找了一些,效果都不理想,不能很好的实现滚动,所以在此将自己实现的方式贴出来,以后或许还会用到!
实现的两种方式
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"/>
代码里进行如下设置:
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 > 0)
txt_mmm.scrollTo(0, scrollAmount);
else
txt_mmm.scrollTo(0, 0);
}
});
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>
代码里进行如下设置:
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(0, txt_info.getBottom());
}
});
注意:两种方式虽能实现这个效果,但具体还是有些许差异,待后续测试完毕再给出结论。