scrollVIew.fullScroll(HorizontalScrollView.FOCUS_RIGHT)无法滚动到末尾。

3
我正在制作一个简单的计算器,设计类似于Google的计算器。我在一个HorizontalScrollView内放置了带有计算式的文本,并且当输入时,我希望它能够自动滚动到计算式的末尾。我已经使用以下Kotlin代码实现了该功能:
textView.addTextChangedListener(object : TextWatcher {

        override fun afterTextChanged(s: Editable) {
            scrollVIew.fullScroll(HorizontalScrollView.FOCUS_RIGHT)
        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
    })

以下是带有scrollView的.xml片段:

<HorizontalScrollView
    android:id="@+id/scrollVIew"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="0"
        android:textAlignment="textEnd"
        android:textSize="75sp" />
</HorizontalScrollView>

这有点奏效了,当文本更新时,文本会滚动到倒数第二个字符,但不是最后一个。有人知道为什么吗?

1个回答

2
只需使用“post”来执行fullScroll:
textView.post { scrollVIew.fullScroll(HorizontalScrollView.FOCUS_RIGHT) }

这是因为在 afterTextChanged 回调中,TextView 的文本尚未完成更改,所以您应该使用 post 在下一个运行循环中执行滚动。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接