3

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.

Source code:

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
      }
    });
  }
}
Patrick
  • 3,578
  • 5
  • 31
  • 53
  • 1
    If I remove the ScrollView, the method `bringPointIntoView` seems to work, but now I'm unable to scroll my TextView... How can I solve this please? – Patrick Mar 22 '11 at 16:32

3 Answers3

8

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.

Patrick
  • 3,578
  • 5
  • 31
  • 53
2

Does adding a movement method to the text view solve the problem?

textView.setMovementMethod(new ScrollingMovementMethod());
James Moore
  • 8,636
  • 5
  • 71
  • 90
  • 1
    Only partly, because there are redraw problems, no fling animation, and no scrollbar. Thanks anyway :) – Patrick May 16 '11 at 19:52
1

Just FYI for anyone else with the same problem, on a listView with large listItems, the overloaded bringPointIntoView can be passed a ListView instead of a ScrollView and use the ScrollTo method instead of smoothScrollTo.

agf
  • 171,228
  • 44
  • 289
  • 238
Kary Payne
  • 11
  • 3