【问题标题】:Force re-layout on a viewgroup including all its children强制重新布局视图组,包括其所有子项
【发布时间】:2014-09-24 20:57:13
【问题描述】:

我正在编写一个可以放大的自定义布局(扩展 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));
}

我正在使用ScaleGestureDetector 来检测“捏缩放”手势并更改布局的比例因子。然后我通过调用requestLayout 在自定义布局上强制布局。不幸的是,这似乎对其子代没有任何影响。即使父母经历了其测量和布局周期,孩子的onMeasureonLayout 也不会被调用。但是,如果我直接在其中一个孩子上调用requestLayout,则该孩子会根据父母中设置的比例因子进行缩放!

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

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

我如何强迫孩子们在给他们的父母打电话 requestLayout 时再次测量自己?

【问题讨论】:

    标签: android android-layout android-view


    【解决方案1】:

    这将强制重新布局视图的子视图(假设视图自身的宽度和高度不需要更改)

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

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 2011-08-24
      • 1970-01-01
      • 2018-03-04
      • 2013-08-30
      • 1970-01-01
      相关资源
      最近更新 更多