Layout (in HorizontalScrollView) not getting updat

2019-09-06 02:38发布

问题:

I have a RelativeLayout (a direct child of a HorizontalScrollView), which stretches beyond the screen bounds, in which I've placed some views dynamically.

In order to capture a part of the view (as a bitmap), I do the following:

v.layout(0, 0, cw, ch);
v.draw(canvas)

And then in order to restore the original bounds (which is the full width of the HSV), call layout() again, but can also scroll till the bounds 0->cw instead of fullWidth.

v.layout(0, 0, fullWidth, fullHeight);
v.invalidate();

I've already tried all the following approaches and as a desperate measure all their combinations:

v.getParent().invalidateChild(v, new Rect(0, 0, width, height));

((Activity)v.getContext()).getWindow().getDecorView().findViewById(android.R.id.content).invalidate();

v.forceLayout();

But the layout doesn't update, until I focus on another view (clicking another button/view).

回答1:

use simple a v.requestLayout();

From the docs:

To initiate a layout, call requestLayout(). This method is typically called by a view on itself when it believes that is can no longer fit within its current bounds.

Further great reading: How Android Draws Views