【问题标题】:Programmatically scroll to end of screen以编程方式滚动到屏幕末尾
【发布时间】:2017-03-18 14:52:08
【问题描述】:

我已经在我的应用程序中实现了TapTargetView 库。

通过某个元素后,此时我需要关注屏幕外的下一个视图:

@Override
public void onSequenceStep(TapTarget lastTarget) {
  if (lastTarget.id() == 7) {
     flavorContainer.setFocusableInTouchMode(true);
     flavorContainer.requestFocus();
  }
}

在我将广告单元添加到屏幕底部之前,一切都很好。所以现在必要的元素显示在广告后面。

方法 requestFocus() 仅将布局滚动到必要的视图可见,但不滚动到屏幕末尾。

我需要一种将屏幕内容滚动到VERY END的方法,而不仅仅是必要的视图在屏幕上变得可见。有可能吗?

布局结构

<android.support.design.widget.CoordinatorLayout>
<LinearLayout>
<android.support.v4.widget.NestedScrollView> 
<LinearLayout> 
<android.support.v7.widget.CardView> 
<LinearLayout>

</LinearLayout> 
</android.support.v7.widget.CardView> 
</LinearLayout> 
</android.support.v4.widget.NestedScrollView> 
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>

【问题讨论】:

    标签: android android-layout android-nestedscrollview


    【解决方案1】:

    您有两种可能的解决方案,各有利弊。

    第一

    NestedScrollView 上使用fullScroll(int) 方法。 NestedScrollView必须在使用此方法之前绘制,焦点将丢失在之前获得它的View上。

    nestedScrollView.post(new Runnable() {
        @Override
        public void run() {
            nestedScrollView.fullScroll(View.FOCUS_DOWN);
        }
    });
    

    第二

    使用方法scrollBy(int,int)/smoothScrollBy(int,int)。它需要更多的代码,但你不会失去当前的焦点:

    nestedScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            final int scrollViewHeight = nestedScrollView.getHeight();
            if (scrollViewHeight > 0) {
                nestedScrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    
                final View lastView = nestedScrollView.getChildAt(nestedScrollView.getChildCount() - 1);
                final int lastViewBottom = lastView.getBottom() + nestedScrollView.getPaddingBottom();
                final int deltaScrollY = lastViewBottom - scrollViewHeight - nestedScrollView.getScrollY();
                /* If you want to see the scroll animation, call this. */
                nestedScrollView.smoothScrollBy(0, deltaScrollY);
                /* If you don't want, call this. */
                nestedScrollView.scrollBy(0, deltaScrollY);
            }
        }
    });
    

    【讨论】:

    • 它工作正常,但我想滚动我的屏幕直到回收站最后一个项目是可能的?如果是,那么如何?
    • method-1 正在工作,但正如你所说,我正在失去焦点。方法 2 不适合我。
    【解决方案2】:

    对我来说,这效果最好。它滚动到底部。

    scrollView.smoothScrollTo(0, scrollView.getChildAt(0).height)
    // scrollview has always only one child
    

    【讨论】:

      猜你喜欢
      • 2017-09-15
      • 1970-01-01
      • 2022-01-10
      • 2015-07-01
      • 1970-01-01
      • 2021-02-06
      • 2011-11-11
      • 2018-07-11
      • 2018-08-20
      相关资源
      最近更新 更多