How to set the starting position of a ScrollView?

后端 未结 6 1607
野趣味
野趣味 2021-01-07 23:36

I have been trying to set the initial position of a scroll View but have not found a way. Does anyone have any ideas? Also I have a GoogleMaps fragment as a children of the

6条回答
  •  天涯浪人
    2021-01-08 00:12

    The problem is that the ScrollView doesn't know its size before it been laid out. A solution is to save the scroll position unil onLayout has been called and then set the scroll position.

    Here is an example (kotlin):

    class MyScrollView constructor(context: Context, attrs: AttributeSet) : ScrollView(context, attrs) {
    
        private var hasStartPositionBeenSet = false
        var startPosition = 0
    
        override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
            super.onLayout(changed, l, t, r, b)
    
            if(!hasStartPositionBeenSet) {
                 scrollTo(0, startPosition)
                 hasStartPositionBeenSet = true
            }
        }
    }
    
    class MyActivity: Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            /* ... */
            findViewById(R.id.scrollView).startPosition = scrollPosition
        }
    }
    

提交回复
热议问题