我想要一个ScrollView从底部开始。任何方法吗?


当前回答

scroll.fullScroll(View.FOCUS_DOWN)将导致焦点的改变。当有多个可聚焦视图(例如两个EditText)时,这将带来一些奇怪的行为。这个问题还有另一种解答方法。

    View lastChild = scrollLayout.getChildAt(scrollLayout.getChildCount() - 1);
    int bottom = lastChild.getBottom() + scrollLayout.getPaddingBottom();
    int sy = scrollLayout.getScrollY();
    int sh = scrollLayout.getHeight();
    int delta = bottom - (sy + sh);

    scrollLayout.smoothScrollBy(0, delta);

这很有效。

芬兰湾的科特林扩展

fun ScrollView.scrollToBottom() {
    val lastChild = getChildAt(childCount - 1)
    val bottom = lastChild.bottom + paddingBottom
    val delta = bottom - (scrollY+ height)        
    smoothScrollBy(0, delta)
}

其他回答

我增加工作完美。

    private void sendScroll(){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {Thread.sleep(100);} catch (InterruptedException e) {}
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
        }).start();
    }

Note

这个答案是一个非常老版本的android的变通方案。今天postDelayed已经没有这个bug了,你应该使用它。

最适合我的是

scroll_view.post(new Runnable() {
     @Override
     public void run() {
         // This method works but animates the scrolling 
         // which looks weird on first load
         // scroll_view.fullScroll(View.FOCUS_DOWN);

         // This method works even better because there are no animations.
         scroll_view.scrollTo(0, scroll_view.getBottom());
     }
});

我尝试成功了。

scrollView.postDelayed(new Runnable() {
    @Override
    public void run() {
        scrollView.smoothScrollTo(0, scrollView.getHeight());
    }
}, 1000);

为什么scroll.fullScroll(view . focus_down)即使包装在.post()中也不能工作的一个可能的原因是视图没有被布局。在这种情况下,View.doOnLayout()可能是一个更好的选择:

scroll.doOnLayout(){
    scroll.fullScroll(View.FOCUS_DOWN)
}

或者,为勇敢的灵魂提供更详细的信息:https://chris.banes.dev/2019/12/03/suspending-views/

这招立竿见影。没有延迟。

// wait for the scroll view to be laid out
scrollView.post(new Runnable() {
  public void run() {
    // then wait for the child of the scroll view (normally a LinearLayout) to be laid out
    scrollView.getChildAt(0).post(new Runnable() {
      public void run() {
        // finally scroll without animation
        scrollView.scrollTo(0, scrollView.getBottom());
      }
    }
  }
}