我想要一个ScrollView从底部开始。任何方法吗?
当前回答
这里有一些滚动到底部的其他方法
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()
}
其他回答
我增加工作完美。
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.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)
}
我尝试成功了。
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.smoothScrollTo(0, scrollView.getHeight());
}
}, 1000);
所有答案的组合对我来说很管用:
扩展函数PostDelayed
private fun ScrollView.postDelayed(
time: Long = 325, // ms
block: ScrollView.() -> Unit
) {
postDelayed({block()}, time)
}
扩展函数measureScrollHeight
fun ScrollView.measureScrollHeight(): Int {
val lastChild = getChildAt(childCount - 1)
val bottom = lastChild.bottom + paddingBottom
val delta = bottom - (scrollY+ height)
return delta
}
扩展函数滚动底部
fun ScrollView.scrollToBottom() {
postDelayed {
smoothScrollBy(0, measureScrollHeight())
}
}
注意,最小延迟应该至少325毫秒,否则滚动将会有bug(不是滚动到整个底部)。当前高度和底部之间的增量越大,延迟时间就应该越大。
scroll.fullScroll(View.FOCUS_DOWN)也应该工作。
把这个放在卷轴里。Post(可运行)
芬兰湾的科特林代码
scrollView.post {
scrollView.fullScroll(View.FOCUS_DOWN)
}
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。