以编程方式滚动到屏幕的末尾

Haz*_*aze 3 android android-layout android-nestedscrollview

我已经将TapTargetView库实现到我的应用程序中.

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

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

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

在此输入图像描述

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

在此输入图像描述

我需要一种方法将屏幕内容滚动到非常结束,而不仅仅是在屏幕上显示必要的视图.可能吗?

在此输入图像描述

布局结构

<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>
Run Code Online (Sandbox Code Playgroud)

Gio*_*oli 34

你有两个可能的解决方案,有利有弊.

第一

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

nestedScrollView.post(new Runnable() {
    @Override
    public void run() {
        nestedScrollView.fullScroll(View.FOCUS_DOWN);
    }
});
Run Code Online (Sandbox Code Playgroud)

第二

使用方法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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


mis*_*o01 7

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

scrollView.smoothScrollTo(0, scrollView.getChildAt(0).height)
// scrollview has always only one child
Run Code Online (Sandbox Code Playgroud)