ScrollView自动滚动实现
2015-11-11 22:23
330 查看
今天写代码时有个场景是,需要向ScrollView中的LinearLayout动态添加TextView,这样当TextView添加到一定数量后,当前屏幕就无法显示最新添加的TextView了,ScrollView默认是不会自动滚动的。那么就需要实现随着新的TextView添加进去后,ScrollView自动滚动到最新添加的TextView。
可以借助ScrollView中的scrollTo(int x,int y)函数来实现,
void android.widget.ScrollView.scrollTo(int x,int y)
Set the scrolled position of your view. This will cause a call to
业务代码很简单,在添加了TextView后,
int offset = LinearLayout.getMeasuredHeight() - scroll.getHeight();
if (offset > 0) {
scroll.scrollTo(0, offset);
}
getMeasuredHeight()是获取控件的实际高度,getHeight()是获取控件显示在屏幕上的高度,比如LinearLayout只有一半内容在屏幕上显示,假设为全屏显示,屏幕高为720,那么getHeight()=720,getMeasuredHeight()=1440.
或者:
handler.post(scrollRunnable);
scrollRunnable = new Runnable() {
@Override
public void run() {
int offset = ll_container.getMeasuredHeight() - scroll.getHeight();
if (offset > 0) {
scroll.scrollTo(0, offset);
}
}
};
可以借助ScrollView中的scrollTo(int x,int y)函数来实现,
void android.widget.ScrollView.scrollTo(int x,int y)
Set the scrolled position of your view. This will cause a call to
onScrollChanged(int, int, int, int)and the view will be invalidated.This version also clamps the scrolling to the bounds of our child.
业务代码很简单,在添加了TextView后,
int offset = LinearLayout.getMeasuredHeight() - scroll.getHeight();
if (offset > 0) {
scroll.scrollTo(0, offset);
}
getMeasuredHeight()是获取控件的实际高度,getHeight()是获取控件显示在屏幕上的高度,比如LinearLayout只有一半内容在屏幕上显示,假设为全屏显示,屏幕高为720,那么getHeight()=720,getMeasuredHeight()=1440.
或者:
handler.post(scrollRunnable);
scrollRunnable = new Runnable() {
@Override
public void run() {
int offset = ll_container.getMeasuredHeight() - scroll.getHeight();
if (offset > 0) {
scroll.scrollTo(0, offset);
}
}
};
相关文章推荐
- Android 用命令行安装应用到手机
- 【Java】Java调用C/C++程序的实现(jni)
- Firefox的extension
- 操作系统,windows编程,网络,socket
- hadoop
- HDOJ 2157 How many ways?? (DP)
- 网页设计注意事项(总结)
- 在电脑上如何配置Oculus
- node.js学习3
- Girls and Boys(匈牙利)
- JDK类Object、Number
- 修改rootfs包的相关操作
- ES6定义函数的新方法(generator和箭头函数)
- 卷积的意义
- hdu1215 七夕节 (预处理,求x的因子和)
- Android IPC之Messenger和AIDL(android开发艺术探索随笔)
- nyoj 116 士兵杀敌(二)【线段树】区间求和
- Spark RDD中Transformation的mapValues、subtract、sample、takeSample详解
- CEF3开发者系列之外篇——IE中JS与C++交互
- 学生——成绩表2.2