2023-03-16 android app java TextView 更新内容时候自动滚到最后一行,使用scrollView.fullScroll(View.FOCUS_DOWN)方式

一、方式一(推荐使用)参考文章可调颜色大小可加粗可设置段落自动滚到最后一行的TextView_texview多行自动滚动_一只爬爬虫的博客-CSDN博客

1、TextView 布局 ,放置ScrollView里面

    <ScrollView
        android:id="@+id/recevie_data"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tv_log"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingHorizontal="14dp"
            android:textColor="#333333"
            android:textSize="16sp" />
    </ScrollView>

2、scrollView.getViewTreeObserver().addOnGlobalLayoutListener()里面执行scrollView.fullScroll(View.FOCUS_DOWN);

scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override

            public void onGlobalLayout() {
                scrollView.post(new Runnable() {
                    public void run() {
                        scrollView.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
});

 3、效果图

二、方式二(效果不好,更新内容老是把第一行隐藏起来,推荐用方式一),参考

Android 如何实现带滚动条的TextView,在更新文字时自动滚动到最后一行? - 简书

1、在布局文件中放置一个TextView,给它添加scrollbars和fadeScrollbars两个属性。

android:fadeScrollbars="false"
android:scrollbars="vertical"
    <TextView
        android:id="@+id/received_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="接收到的数据:"
        android:fadeScrollbars="false"
        android:scrollbars="vertical"/>

2、onCreate()方法中用setMovementMethod(ScrollingMovementMethod.getInstance());方法配置TextView的滚动方式。

m_received_data.setMovementMethod(ScrollingMovementMethod.getInstance());

3、更新内容后,使用View的scrollTo(int x,int y)方法使其自动滚动到最后一行。

m_received_data.append(msg);
int offset = m_received_data.getLineCount() * m_received_data.getLineHeight();
if(offset > m_received_data.getHeight()){
      m_received_data.scrollTo(0,offset- m_received_data.getHeight());
}

4、清空内容后需要用m_received_data.scrollTo(0,0) 恢复滚轮位置

 5、效果

猜你喜欢

转载自blog.csdn.net/qq_37858386/article/details/129586019