将TextView滚动到指定位置

3

我想滚动TextView以使特定位置的文本可见。我该怎么做?我尝试了bringPointIntoView(int offset)但没有成功。

源代码:

public class TextScrollActivity extends Activity {
  public void onCreate (final Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);
    final int position = 500;
    final TextView textView = new TextView (this);
    final ScrollView scrollView = new ScrollView (this);
    scrollView.addView (textView);
    Button button = new Button (this);
    button.setText ("Scroll to " + position);
    LinearLayout layout = new LinearLayout (this);
    layout.setOrientation (LinearLayout.VERTICAL);
    layout.addView (scrollView,
    new LayoutParams (LayoutParams.FILL_PARENT, 200));
    layout.addView (button, new LayoutParams (LayoutParams.FILL_PARENT,
    LayoutParams.WRAP_CONTENT));
    StringBuilder builder = new StringBuilder ();
    for (int i = 0; i < 1000; i++)
      builder.append (String.format ("[ %05d ] ", i));
    textView.setText (builder);
    setContentView (layout);
    button.setOnClickListener (new OnClickListener () {
      public void onClick (View v) {
        System.out.println (textView.bringPointIntoView (position * 10));
        // scrollView.scrollTo (0, position * 10); // no
      }
    });
  }
}

1
如果我移除ScrollView,bringPointIntoView方法似乎可以工作,但现在我无法滚动我的TextView...请问我该如何解决这个问题? - Patrick
3个回答

8

对于那些有同样问题的人,我最终自己实现了bringPointIntoView函数:

  public static void bringPointIntoView (TextView textView,
  ScrollView scrollView, int offset)
  {
    int line = textView.getLayout ().getLineForOffset (offset);
    int y = (int) ((line + 0.5) * textView.getLineHeight ());
    scrollView.smoothScrollTo (0, y - scrollView.getHeight () / 2);
  }

如果您有更好的解决方案,请不要犹豫。


如何处理HorizontalScrollView? - tuantv.dev

2
给 TextView 添加移动方法可以解决这个问题吗?
textView.setMovementMethod(new ScrollingMovementMethod());

1
只能部分地显示,因为存在重绘问题,没有惯性滑动动画和滚动条。不管怎样还是谢谢 :) - Patrick

1

提供给有同样问题的人一个小提示,在具有大型列表项的 listView 上,可以将重载的 bringPointIntoView 方法传递一个 ListView 而不是 ScrollView,并使用 ScrollTo 方法而不是 smoothScrollTo


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接