ScrollView scrollTo doesn't work

前端 未结 4 907
日久生厌
日久生厌 2021-01-02 19:41

Same issue as ScrollView .scrollTo not working? Saving ScrollView position on rotation

I dynamically add items to scrollView in onCreate. I try the following after a

4条回答
  •  庸人自扰
    2021-01-02 20:01

    You don't need to extend the ScrollView and create your own as per the answer provided by David Daudelin for the this question.

    Get the ViewTreeObserver of the ScrollView and add an OnGlobalLayoutListener to the ViewTreeObserver. Then call the ScrollView.scrollTo(x,y) method from the onGlobalLayout() method of the OnGlobalLayoutListener. Code:

     ScrollView mainScroll = (ScrollView) findViewById(R.id.average_scroll_mainScroll);
    
     ViewTreeObserver vto = scrollView.getViewTreeObserver();
     vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
          public void onGlobalLayout() {
               mainScroll.scrollTo(0, 0);
          }
     });
    

提交回复
热议问题