【问题标题】:How to scroll to a given line number, TextView inside ScrollView如何滚动到给定的行号,ScrollView中的TextView
【发布时间】:2015-04-07 04:23:30
【问题描述】:

我在 ScrollView 中有一个 TextView。我想滚动文本,使已知的行号或多或少垂直居中。这应该不难,但似乎如此。我还没有看到任何专门解决滚动到给定行号问题的帖子或教程。

经过我的研究,我认为它应该像这样工作......

scroller.scrollTo(0, lineNumb * html.getLineHeight());

其中scroller是ScrollView的R.Id,html是TextView,而lineNumb显然是行号,但文本不会移动。

我已经把它变成了一个runnable,但仍然没有乐趣......

scroller.post(new Runnable() {
    public void run() {
    scroller.scrollTo(0, lineNumb * html.getLineHeight());}});

我花了一整天的时间试图弄清楚这一点,研究了许多帖子、教程等,但我陷入了死胡同。我一定错过了一些非常简单的东西。希望你能帮忙。

米克

【问题讨论】:

    标签: java android textview scrollview


    【解决方案1】:

    您可以像这样按行号在ScrollView 内滚动textView

    textView.setText(text);
    final int lineNumber = 20;
    scroller.post(new Runnable() {
        @Override
        public void run() {
            int y = textView.getLayout().getLineTop(lineNumber);
            scroller.scrollTo(0, y);
        }
    });
    

    此外,您只能滚动 textView 而无需换行 scrollView

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:maxLines="10"
        android:padding="16dp"/>
    

    滚动textView

    TextView textView = (TextView) findViewById(R.id.text);
    textView.setMovementMethod(new ScrollingMovementMethod());
    final int lineNumber = 20
    textView.post(new Runnable() {
        @Override
        public void run() {
            int y = textView.getLayout().getLineTop(lineNumber);
            textView.scrollTo(0, y);
        }
    });
    

    希望对你有用。

    【讨论】:

    • 当您的代码不起作用时,我检查了我的 xml 文件 - TextView 不在 ScrollView 内! :(我已经正确地开始了,但我认为当我使用设计视图进行清理时它被移动了。我很高兴知道我不需要滚动视图 - 越简单越好:)
    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 2018-02-19
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    相关资源
    最近更新 更多