将 TextView 滚动到文本位置 [英] Scroll TextView to text position

查看:32
本文介绍了将 TextView 滚动到文本位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想滚动我的 TextView 以使文本中的特定位置可见.我怎样才能做到这一点?我尝试了 bringPointIntoView (int offset) 但没有成功.

I want to scroll my TextView to make visible a specific position in the text. How can I do that? I tried bringPointIntoView (int offset) but without success.

源代码:

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
      }
    });
  }
}

推荐答案

对于有同样问题的朋友,我终于自己实现了bringPointIntoView:

For those who have the same problem, I finally made my own implementation of 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);
  }

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

Don't hesitate if you have a better solution.

这篇关于将 TextView 滚动到文本位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆