TextView更新文本时自动滑动到最后一行

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());
    }
});

注意:两种方式虽能实现这个效果,但具体还是有些许差异,待后续测试完毕再给出结论。

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

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值