Avi Brenner
Avi Brenner

Reputation: 161

How to clear the measure cache android

I have an app that lays out controls on the screen at runtime, it passes through each control calling measure on a View with a provided width and WRAP_CONTENT as height.

It does this before any data is set on the view to show a stencil version of the view and then after actual data is set on the view.

The issue is that since it calls measure twice with same input, the second time we hit the measure cache and it doesn't re-measure even though the actual measurements of the view have changed since data on the controls have changed.

Is there any way to force it to re-measure on the second call?

Upvotes: 3

Views: 480

Answers (2)

RobCo
RobCo

Reputation: 6495

You can use View.forceLayout to invalidate the cache and force a full layout pass.
The source code shows what it does:

/**
 * Forces this view to be laid out during the next layout pass.
 * This method does not call requestLayout() or forceLayout()
 * on the parent.
 */
public void forceLayout() {
    if (mMeasureCache != null) mMeasureCache.clear();

    mPrivateFlags |= PFLAG_FORCE_LAYOUT;
    mPrivateFlags |= PFLAG_INVALIDATED;
}

Upvotes: 1

Stefan Haustein
Stefan Haustein

Reputation: 18793

I haven't found a way to clear the cache, but if one of the values is UNSPECIFIED, it looks like a cache mismatch can be forced similar to this:

int fakeSpace = (int) (Math.random() * 9999999);
int spec = View.MeasureSpec.makeMeasureSpec(fakeSpace, View.MeasureSpec.UNSPECIFIED);
view.measure(spec, spec);

Upvotes: 0

Related Questions