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


当前回答

如果你的最低SDK是29或更高,你可以使用这个:

View childView = findViewById(R.id.your_view_id_in_the_scroll_view)
if(childView != null){
  scrollview.post(() -> scrollview.scrollToDescendant(childView));
}

其他回答

这并不是问题的确切答案,但我需要在EditText获得焦点后立即向下滚动。然而,公认的答案将使ET也失去焦点(我假设ScrollView)。

我的解决方案如下:

emailEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus){
            Toast.makeText(getActivity(), "got the focus", Toast.LENGTH_LONG).show();
            scrollView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }
            }, 200);
        }else {
            Toast.makeText(getActivity(), "lost the focus", Toast.LENGTH_LONG).show();
        }
    }
});

需要考虑的一件事是不设置什么。确保您的子控件,特别是EditText控件,没有RequestFocus属性集。这可能是布局中最后解释的属性之一,它将覆盖其父(布局或ScrollView)上的重力设置。

在这种情况下,我们只使用滚动。scrollTo(0, sc.getBottom())不工作,使用它使用scroll.post

例子:

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

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

// 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());
      }
    }
  }
}

您应该在滚动中运行代码。像这样发帖:

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