我想要一个ScrollView从底部开始。任何方法吗?
当前回答
需要考虑的一件事是不设置什么。确保您的子控件,特别是EditText控件,没有RequestFocus属性集。这可能是布局中最后解释的属性之一,它将覆盖其父(布局或ScrollView)上的重力设置。
其他回答
当视图尚未加载时,您不能滚动。你可以“稍后”用上面的post或sleep call来做这件事,但这不是很优雅。
最好计划滚动并在下一个onLayout()中执行。示例代码如下:
https://stackoverflow.com/a/10209457/1310343
如果你的最低SDK是29或更高,你可以使用这个:
View childView = findViewById(R.id.your_view_id_in_the_scroll_view)
if(childView != null){
scrollview.post(() -> scrollview.scrollToDescendant(childView));
}
这里有一些滚动到底部的其他方法
fun ScrollView.scrollToBottom() {
// use this for scroll immediately
scrollTo(0, this.getChildAt(0).height)
// or this for smooth scroll
//smoothScrollBy(0, this.getChildAt(0).height)
// or this for **very** smooth scroll
//ObjectAnimator.ofInt(this, "scrollY", this.getChildAt(0).height).setDuration(2000).start()
}
使用
如果你的滚动视图已经布局
my_scroll_view.scrollToBottom()
如果你的滚动视图没有完成布局(例如:你滚动到底部的活动onCreate方法…)
my_scroll_view.post {
my_scroll_view.scrollToBottom()
}
我尝试成功了。
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.smoothScrollTo(0, scrollView.getHeight());
}
}, 1000);
有人说scrollView。Post没用。
如果你不想用scrollView。postDelayed,另一种选择是使用侦听器。下面是我在另一个用例中所做的:
ViewTreeObserver.OnPreDrawListener viewVisibilityChanged = new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
if (my_view.getVisibility() == View.VISIBLE) {
scroll_view.smoothScrollTo(0, scroll_view.getHeight());
}
return true;
}
};
你可以这样把它添加到视图中:
my_view.getViewTreeObserver().addOnPreDrawListener(viewVisibilityChanged);
推荐文章
- Android加载JS包失败
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 如何在android中复制一个文件?
- adb找不到我的设备/手机(MacOS X)