Android: Notify Scrollview that it's child's size has changed: how?

别等时光非礼了梦想. 提交于 2019-11-28 11:38:08
Frank

I found a solution after trying just about every onXXX() method. onLayout can be used. You can plan the scroll and do it later in onLayout().

Extend your scrollview, and add:

private int onLayoutScrollByX = 0;
private int onLayoutScrollByY = 0;

public void planScrollBy(int x, int y) {
    onLayoutScrollByX += x;
    onLayoutScrollByY += y;
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    doPlannedScroll();
}

public void doPlannedScroll() {
    if (onLayoutScrollByX != 0 || onLayoutScrollByY != 0) {
        scrollBy(onLayoutScrollByX, onLayoutScrollByY);
        onLayoutScrollByX = 0;
        onLayoutScrollByY = 0;
    }
}

Now, to use this in your code, instead of scrollBy(x,y) use planScrollBy(x,y). It will do the scroll at a time when the new size of the child is "known", but not displayed on screen yet.

When you use a horizontal or vertical scrollview, of course you can only scroll one way, so you will have to change this code it a bit (or not, but it will ignore the scroll on the other axis). I used a TwoDScrollView, you can find it on the web.

You can call:

scrollView.updateViewLayout(childView, childLayout)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!