java - 将 TextView 滚动到文本位置

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

最佳答案

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

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

关于java - 将 TextView 滚动到文本位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5289575/

相关文章:

java - 内部类中有变量

java - Java 8 中 Collections.sort 的问题

android - 每个 ABI 的不同库搜索路径

android - 如何在 Android Jetpack Compose 的文本行末尾显示省略号(三个点)?

javascript - 在 Firefox 中禁用主窗口滚动 onmouseenter iframe

javascript - 如何在 React 中滚动时切换图像(就像在 Apple 网站上一样)?

java - 如何限制用户只能输入1-3

java - 在 Windows 7 上控制 setLocation 偏移 4px

java - 如何使用 viewHolder 模式让 UI 元素在 listView 中滚动?

javascript - 点击菜单页面跳转到顶部