gpt4 book ai didi

android - 在android中自动滚动TextView以将文本显示在 View 中

转载 作者:IT王子 更新时间:2023-10-28 23:46:18 25 4
gpt4 key购买 nike

我有一个 TextView,我正在向其中动态添加文本。

在我的 main.xml 文件中,我设置了属性以使我的最大行数为 19 并且滚动条垂直。

.java 文件中,我使用 textview.setMovementMethod(new ScrollingMovementMethod()); 来允许滚动。

滚动效果很好。一旦占用了 19 行,并添加了更多行,它就会开始正常滚动。问题是,我希望新文本滚动到 View 中。

我正在写出 textview.getScrollY() 的值,无论如何它都保持在 0 (即使我手动向下滚动并添加新行文本)。

因此 textview.scrollTo(0, textview.getScrollY()); 对我没有任何作用。

我应该使用另一种方法来获取 textview 的垂直滚动量吗?我读过的所有内容都表明,出于所有 Intent 和目的,我正在做的事情应该是有效的:/

最佳答案

对 TextView 源进行了一些挖掘,但这就是我想出的。它不需要您将 TextView 包装在 ScrollView 中,据我所知,它可以完美运行。

// function to append a string to a TextView as a new line
// and scroll to the bottom if needed
private void addMessage(String msg) {
// append the new string
mTextView.append(msg + "\n");
// find the amount we need to scroll. This works by
// asking the TextView's internal layout for the position
// of the final line and then subtracting the TextView's height
final int scrollAmount = mTextView.getLayout().getLineTop(mTextView.getLineCount()) - mTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
mTextView.scrollTo(0, scrollAmount);
else
mTextView.scrollTo(0, 0);
}

如果您发现失败的情况,请告诉我。如果能够修复我的应用程序中的任何错误,我将不胜感激;)

编辑:我应该提到我也使用

mTextView.setMovementMethod(new ScrollingMovementMethod());

在实例化我的 TextView 之后。

关于android - 在android中自动滚动TextView以将文本显示在 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3506696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com