Can't Scroll To Auto Middle of TextView in Kotlin using ScrollTo

173 views Asked by At

I am decently experienced in Java, but brand new to Kotlin and Android development (I hope learning Kotlin pays off in the end). On certain scenarios, I want my scrollable TextView to autoscroll toa certain spot of the text view and scroll to the bottom on other scenarios.

I found I can use the scrollTo() method to scroll to a desired Y-value. Since the length of my text changes though, I can't find a method to get the exact height of the entire scrolling textview. However, I can multiply the line count by the line height to find the proper height. So this will work perfectly. HOWEVER, the line count does not update immediately, in fact, it seems to update after the entire event of pushing a button to update the textview finishes. If I click it again, then the text scrolls to the proper height. It appears I would need to call the method twice, but I feel like I am missing something. The first time I run it, the line count is 0, making the scroll to height 0, thus the textview scrolls to the very top of the screen.

Since I am not using a ScrollView and not using Java, a lot of the other answers on Stack Overflow seemed helpful but irrelevant.

Thanks,

JT

1

There are 1 answers

0
omz1990 On BEST ANSWER

For these sort of issues where the height of elements change after the content has been added, I do the following, and since you are using kotlin, it'll be easier.

Create an extension function for View to call a function after the measurement has been complete (i.e. the content is fully loaded). Like:

object ViewExtension {

    // Extension function
    inline fun <T : View> T.afterMeasureComplete(crossinline f: T.() -> Unit) {
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                if (viewTreeObserver.isAlive) {
                    if (measuredWidth > 0 && measuredHeight > 0) {
                        viewTreeObserver.removeOnGlobalLayoutListener(this)
                        f()
                    }
                }
            }
        })
    }
}

Then in your Activity/Fragment

// import the extension function
import you.package.and.directory.util.ViewExtension.afterMeasureComplete

// Then after you have initialized your TextView, do this:
yourTextView.afterMeasureComplete {
    // Now get the height of the text view, and scroll to your desired position
}

Works for me ;)