强制重新布局视图组,包括其所有子项

use*_*994 5 android android-layout android-view

我正在编写一个FrameLayout可以放大的自定义布局(扩展).它的所有子节点也是自定义视图,它实际上通过getter方法从父节点获得比例因子,并通过设置缩放尺寸来相应缩放

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    float scaleFactor = ((CustomLayout) getParent()).getCurrentScale();
    setMeasuredDimension((int) (getMeasuredWidth() * scaleFactor), (int) (getMeasuredHeight() * scaleFactor));
}
Run Code Online (Sandbox Code Playgroud)

我正在使用a ScaleGestureDetector来检测"缩放缩放"手势并更改布局的scaleFactor.然后我通过调用强制在自定义布局上的布局requestLayout.不幸的是,这似乎对其孩子没有任何影响.孩子们的onMeasure&onLayout即使父经历其措施和布局周期永远不会被调用.但是,如果我直接打电话requestLayout给其中一个孩子,那么这个孩子就会根据父母设定的比例因子进行缩放!

似乎除非requestLayout在视图上专门调用,否则它实际上不会再次测量自身,而是使用某种缓存.从视图的源代码中可以看出这一点

if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
        // Only trigger request-during-layout logic if this is the view requesting it,
        // not the views in its parent hierarchy
        ViewRootImpl viewRoot = getViewRootImpl();
        if (viewRoot != null && viewRoot.isInLayout()) {
            if (!viewRoot.requestLayoutDuringLayout(this)) {
                return;
            }
        }
        mAttachInfo.mViewRequestingLayout = this;
    }
Run Code Online (Sandbox Code Playgroud)

我如何强迫孩子们再次拜访requestLayout他们的父母?

Hel*_*ang 5

这将强制中继视图的子级(鉴于视图自身的宽度和高度不需要更改)

private static void relayoutChildren(View view) {
    view.measure(
        View.MeasureSpec.makeMeasureSpec(view.getMeasuredWidth(), View.MeasureSpec.EXACTLY),
        View.MeasureSpec.makeMeasureSpec(view.getMeasuredHeight(), View.MeasureSpec.EXACTLY));
    view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
}
Run Code Online (Sandbox Code Playgroud)