2014-09-24 13 views
5

我正在編寫一個可以放大的自定義佈局(它擴展了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強制定製佈局上的佈局。不幸的是,這似乎對其子女沒有任何影響。孩子的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; 
    } 

如何強制孩子們還就呼籲他們的父母requestLayout再次去衡量自己是顯而易見的?

回答

4

這將迫使重新佈局視圖的孩子(因爲觀點本身的寬度和高度並不需要改變)

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()); 
} 
相關問題