Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling a TextView to a specific line

I have a TextView inside a ScrollView. Let's say the ScrollView is named s and the TextView is named t.

I have many lines to be displayed in the TextView and at the same time I want to scroll the view to a specific line.

So I did this:

t.setText(aVeryLongString);
int y = t.getLayout().getLineTop(40); // e.g. I want to scroll to line 40
s.scrollTo(0, y);

But it won't scroll, except the second time. It seems that on the first time the code finishes, the ScrollView knows how much the total height of the TextView is.

So I think there must be something to force calculating the needed height before the scrollTo call. How to do that (or otherwise)?

like image 515
Randy Sugianto 'Yuku' Avatar asked Dec 22 '09 10:12

Randy Sugianto 'Yuku'


1 Answers

Found the answer here.

Instead of calling scrollTo directly, we must call post instead on the ScrollView. This works.

t.setText(aVeryLongString);
s.post(new Runnable() {
    @Override
    public void run() {
        int y = t.getLayout().getLineTop(40); // e.g. I want to scroll to line 40
        s.scrollTo(0, y);
    }
});
like image 133
Randy Sugianto 'Yuku' Avatar answered Sep 19 '22 00:09

Randy Sugianto 'Yuku'