以编程方式滚动到屏幕底部

17
我已经将 TapTargetView 库实现到我的应用程序中。在通过某个元素后,我需要聚焦于此时位于屏幕外的下一个视图。
@Override
public void onSequenceStep(TapTarget lastTarget) {
  if (lastTarget.id() == 7) {
     flavorContainer.setFocusableInTouchMode(true);
     flavorContainer.requestFocus();
  }
}

在底部添加广告单元之前,一切都很好。现在必要的元素显示在广告的后面。

enter image description here

requestFocus()方法只滚动布局以使所需视图可见,而不是滚动到屏幕末端。

enter image description here

我需要一个可以将屏幕内容滚动到最底部的方法,而不仅仅是让必要的视图在屏幕上可见。这可能吗?

enter image description here

布局结构

<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>
2个回答

62

你有两种可能的解决方案,它们各有优缺点。

第一种

使用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);
        }
    }
});

它运行得很好,但我想滚动屏幕直到回收站的最后一个项目,这是可能的吗?如果可以,怎么做? - Arbaz.in
1
方法一可以运行,但正如你所说,我失去了焦点。方法二对我来说不起作用。 - K Pradeep Kumar Reddy

11

对我来说,这个方法效果最好。它可以滚动到页面底部。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接