在android中自动滚动TextView以将文本带入视野 [英] auto-scrolling TextView in android to bring text into view

查看:20
本文介绍了在android中自动滚动TextView以将文本带入视野的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a TextView that I'm dynamically adding text to.

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

in my main.xml file I have the properties set to make my max lines 19 and scrollbars vertical.

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

in the .java file I am using textview.setMovementMethod(new ScrollingMovementMethod()); to allow for scrolling.

滚动效果很好.一旦占用了 19 行,并且添加了更多行,它就会开始按原样滚动.问题是,我希望新文本滚动到视图中.

The scrolling works great. As soon as 19 lines are taken up, and more lines are added it starts scrolling just as it should. The problem is, I want the new text to scroll into view.

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

I am writing out the value for textview.getScrollY() and it stays at 0 no matter what (even if I manually scroll it down and add a new line of text).

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

consequently textview.scrollTo(0, textview.getScrollY()); does nothing for me.

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

Is there another method I should be using to obtain the vertical scroll amount for the textview? Everything I've read says that for all intents and purposes, what I'm doing should be working :/

推荐答案

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

Took some digging through the TextView source but here's what I came up with. It doesn't require you to wrap the TextView in a ScrollView and, as far as I can tell, works perfectly.

// 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 + "
");
    // 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);
}

如果您发现此操作失败的情况,请告诉我.我很高兴能够修复我的应用程序中的任何错误 ;)

Please let me know if you find a case where this fails. I'd appreciate being able to fix any bugs in my app ;)

我应该提到我也使用

mTextView.setMovementMethod(new ScrollingMovementMethod());

在实例化我的 TextView 之后.

after instantiating my TextView.

这篇关于在android中自动滚动TextView以将文本带入视野的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆