简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM