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 scrollbar
Based on the answer from KNfLrPn , and correcting some issues from that answer, there is a solution that is still valid in Android Studio 3.4.2 in 2019 and that I've tested in my developing app.
private void addMessage(String msg) {
mTextView.append(msg + "\n");
final int scrollAmount =
max(mTextView.getLayout().getLineBottom(
mTextView.getLineCount()-1) - mTextView.getHeight(),0);
mTextView.post(new Runnable() {
public void run() {
mTextView.scrollTo(0, mScrollAmount +
mTextView.getLineHeight()/3);
}});
mTextView.scrollTo(0, scrollAmount);
}
There were some problems, some of them pointed out in the comments and other answers:
a) The line mTextView.getLayout().getLineTop(mTextView.getLineCount()) gives a bound error. The equivalent to mTextView.getLayout().getLineTop(L) is mTextView.getLayout().getLineBottom(L-1). So I've replaced it by the line
mTextView.getLayout().getLineBottom(
mTextView.getLineCount()-1) - mTextView.getHeight()
b) The max is just for simplify the logic
c) scrollTo should appear within a post method in a kind of thread.
d) plain vanilla last line bottom doesn't solve the problem completely apparently because there is a bug that the last line of TextView that should appear completely in the view, appears cut off. So I add about 1/3 of the height of the line to the scroll. This can be calibrated, but it has worked well for me.
-/-
Sometimes what seems obvious needs to be said: The value of x and y corresponds to the scrollTo routine exactly matches the number of pixels in the text that is invisible on the left (x) and the number of pixels in the text that is invisible on the top (y). This corresponds exactly to the value of the widgets scrollX and scrollY properties.
Thus, when one takes the y from the last line of the text, and if this is a value greater than the widget's height, it must correspond exactly to the number of pixels of the text that needs to be hidden, which is entered as a parameter of the scrollTo method.
The third of the height of the line that I've added, put the scroll a little higher, making the last line fully visible, precisely because of practice does not correspond exactly to what the theory advocates.