【问题标题】:Scroll TextView to text position将 TextView 滚动到文本位置
【发布时间】:2011-08-14 13:13:32
【问题描述】:

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

【问题讨论】:

  • 如果我删除了 ScrollView,bringPointIntoView 方法似乎可以工作,但现在我无法滚动我的 TextView... 请问我该如何解决这个问题?

标签: java android scroll position textview


【解决方案1】:

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

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

【讨论】:

  • Horizo​​ntalScrollView如何处理?
【解决方案2】:

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

textView.setMovementMethod(new ScrollingMovementMethod());

【讨论】:

  • 只有一部分,因为有重绘问题,没有fling动画,也没有滚动条。无论如何谢谢:)
【解决方案3】:

对于遇到相同问题的其他人仅供参考,在带有大 listItemslistView 上,重载的 bringPointIntoView 可以传递 ListView 而不是 ScrollView 并改用 ScrollTo 方法smoothScrollTo.

【讨论】:

    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    相关资源
    最近更新 更多