自动滚动在Android中的TextView,使文本视图 [英] auto-scrolling TextView in android to bring text into view

查看:281
本文介绍了自动滚动在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(新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的在滚动型和,据我所知道的,完美的作品。

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

请让我知道如果你发现哪里失败的情况。我倒是AP preciate能够解决我的应用程序的任何错误;)

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

编辑:我要指出,我还用

I should mention that I also use

mTextView.setMovementMethod(new ScrollingMovementMethod());

在我的实例TextView的。

after instantiating my TextView.

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

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