I have a TextView
that I'm dynamically adding text to.
in my main.xml
file I have the properties set to make my max lines 19 and scrollbars vertical.
in the .java
file I am using textview.setMovementMethod(new ScrollingMovementMethod());
to allow for scrolling.
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.
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).
consequently textview.scrollTo(0, textview.getScrollY());
does nothing for me.
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 :/
To make TextView scrollable, you don't need to use ScrollView, just add android:scrollbars=”vertical” attribute in TextView and then add two line of code in your java activity file. Following is the xml layout file which contain a LinearLayout and a TextView.
for the new line in TextView just add \n in middle of your text it works..
In Android, a ScrollView is a view group that is used to make vertically scrollable views. A scroll view contains a single direct child only. In order to place multiple views in the scroll view, one needs to make a view group(like LinearLayout) as a direct child and then we can define many views inside it.
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); }
Please let me know if you find a case where this fails. I'd appreciate being able to fix any bugs in my app ;)
Edit: I should mention that I also use
mTextView.setMovementMethod(new ScrollingMovementMethod());
after instantiating my TextView.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With