【问题标题】:android scrollview scroll to top direction when new view added添加新视图时,android滚动视图滚动到顶部方向
【发布时间】:2025-12-09 07:40:01
【问题描述】:

在滚动视图中,如果我在中间添加任何视图,通常添加视图下方的所有视图都会向下滚动。但我想在不干扰底部视图的情况下将添加视图的顶部视图滚动到上方。是否可以在滚动视图中,请帮助我?

图中,如果添加了视图4,那么视图1必须向上滚动,而不改变视图2和视图3的位置。

【问题讨论】:

    标签: android views scrollview


    【解决方案1】:

    您可能可以获得要添加的视图的高度,然后手动滚动滚动视图那么多像素

    scrollView.scrollBy(0, viewAdded.getHeight())

    【讨论】:

      【解决方案2】:

      我想试这个问题很久了,今天终于有机会了。该方法非常简单(事实上,@dweebo 之前已经提到过)——我们在添加视图时将ScrollView 向上移动。为了在添加时获得精确(有效)的尺寸,我们使用ViewTreeObserver。以下是您可以从中获得提示的代码:

          // Getting reference to ScrollView
          final ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
          // Assuming a LinearLayout container within ScrollView
          final LinearLayout parent = (LinearLayout) findViewById(R.id.parent);
      
          // The child we are adding
          final View view = new View(ScaleActivity.this);
          LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100);
          view.setLayoutParams(params);
      
          // Finally, adding the child
          parent.addView(view, 2); // at index 2
      
          // This is what we need for the dimensions when adding
          ViewTreeObserver viewTreeObserver = parent.getViewTreeObserver();
          viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
              @Override
              public boolean onPreDraw() {
                  parent.getViewTreeObserver().removeOnPreDrawListener(this);
      
                  scrollView.scrollBy(0, view.getHeight());
                  // For smooth scrolling, run below line instead
                  // scrollView.smoothScrollBy(0, view.getHeight())
      
                  return false;
              }
          });
      

      【讨论】: