您的位置:首页 > 其它

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
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);

                }

            }

        };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: