[英]Scroll TextView to text position
I want to scroll my TextView to make visible a specific position in the text. 我想滚动我的TextView以使其在文本中的特定位置可见。 How can I do that?
我怎样才能做到这一点? I tried bringPointIntoView (int offset) but without success.
我尝试了BringPointIntoView(int offset),但是没有成功。
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
}
});
}
}
For those who have the same problem, I finally made my own implementation of bringPointIntoView: 对于那些有同样问题的人,我终于实现了我自己的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.setMovementMethod(new ScrollingMovementMethod());
仅供参考,对于有相同问题的其他任何人,在具有大listItems
的listView
上,可以将重载的bringPointIntoView
传递给ListView
而不是ScrollView
并使用ScrollTo
方法而不是smoothScrollTo
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.