今天写代码时有个场景是,需要向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
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);
}
}
};
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);
}
}
};