将TextView滚动到文本位置

时间:2011-03-13 13:17:12

标签: java android scroll position textview

我想滚动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
      }
    });
  }
}

3 个答案:

答案 0 :(得分:4)

对于那些有同样问题的人,我终于自己实现了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);
  }

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

答案 1 :(得分:1)

在文本视图中添加移动方法是否可以解决问题?

textView.setMovementMethod(new ScrollingMovementMethod());

答案 2 :(得分:1)

对于有同样问题的其他任何人,只要对于listView listItems bringPointIntoView来说,重载的ListView可以传递ScrollView而不是{{1}并使用ScrollTo方法代替smoothScrollTo