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.