How to scroll tablayout programmatically - Android

前端 未结 13 2356
终归单人心
终归单人心 2021-02-07 00:31

I have created 30 scrollable tabs using tablayout.

So first three tabs are visible on screen and rest of them are invisible which can be scroll using swipe gesture.

13条回答
  •  故里飘歌
    2021-02-07 00:45

    The code snippet below works for me

    class TriggerOnceListener(private val v: View, private val block: () -> Unit) : ViewTreeObserver.OnPreDrawListener {
        override fun onPreDraw(): Boolean {
            block()
            v.viewTreeObserver.removeOnPreDrawListener(this)
            return true
        }
    }
    
    fun onCreate() {
        val position = ***The tab position you want to scroll to, 29 for your case here***
        tabLayout.let { it.viewTreeObserver.addOnPreDrawListener(TriggerOnceListener(it)
        { it.setScrollPosition(position, 0f, true) } ) }
    }
    

    I dived into Tab.select(), and found Android uses Tablayout.setScrollPosition() to do this scrolling. And in onCreate() the widgets have not been measured, you need to postpone the call until layout is complete.

提交回复
热议问题