将 TextView 滚动到特定行 [英] Scrolling a TextView to a specific line
问题描述
我在 ScrollView 中有一个 TextView.假设 ScrollView 名为 s
,TextView 名为 t
.
I have a TextView inside a ScrollView. Let's say the ScrollView is named s
and the TextView is named t
.
我有很多行要显示在 TextView 中,同时我想将视图滚动到特定行.
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.
所以我这样做了:
t.setText(aVeryLongString);
int y = t.getLayout().getLineTop(40); // e.g. I want to scroll to line 40
s.scrollTo(0, y);
但它不会滚动,除了第二次.似乎在代码第一次完成时,ScrollView 就知道 TextView 的总高度是多少.
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.
所以我认为必须在 scrollTo 调用之前强制计算所需的高度.如何做到这一点(或以其他方式)?
So I think there must be something to force calculating the needed height before the scrollTo call. How to do that (or otherwise)?
推荐答案
找到答案 此处.
我们必须在 ScrollView 上调用 post
而不是直接调用 scrollTo
.这有效.
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);
}
});
这篇关于将 TextView 滚动到特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!