2017-03-08 1104 views
0

我正在創建新的ViewGroup。新視圖將繪製一些圓圈。該視圖應該有5個初始圓圈,所以我希望將它們均勻地分佈在視圖的寬度上,並且還要跟蹤它們(它們的中心(x,y)位置),以便在視圖爲無效。什麼時候應根據其尺寸繪製自定義佈局

這是我onMeasure

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
{ 
    int desiredWidth = getPaddingLeft() + getPaddingRight() + PREFERED_SIZE; 
    int desiredHeight = getPaddingTop() + getPaddingBottom() + PREFERED_SIZE; 

    actualWidth = resolveSizeAndState(desiredWidth,widthMeasureSpec,0); 
    actualHeight = resolveSizeAndState(desiredHeight,heightMeasureSpec,0); 
    setMeasuredDimension(actualWidth, actualHeight); 
} 

什麼我不知道的是當我要補充這些圈子。 onMeasure可以多次調用,並獲得不同的寬度和高度值,所以我不知道什麼時候應該計算初始圓圈的(x,y)..在onMeasure裏面?在onDraw開頭?

回答

0

只是檢查的文檔。還有就是在測量部分3個回調和我猜你可以在最後一個做:https://developer.android.com/reference/android/view/View.html

  • onMeasure(int, int)調用,以確定該視圖及其所有子項的大小要求。
  • onLayout(boolean, int, int, int, int)當此視圖應爲其所有子項指定大小和位置時調用。
  • onSizeChanged(int, int, int, int)當此視圖的大小發生變化時調用。

所以我想你的計算最好的是onSizeChanged

0

您可以使用View.OnLayoutChangeListener跟蹤佈局的變化:

public class CustomView extends View implements View.OnLayoutChangeListener { 

    private int height; 
    private int width; 

    public CustomView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     // add the layout listener 
     addOnLayoutChangeListener(this); 
    } 

    @Override 
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { 
     height = getHeight(); 
     width = getWidth(); 
    } 

} 
+0

它看起來幾乎完全像onMeasure? –

+0

不完全,'onMeasure'被調用的次數多於'onLayoutChange'。每當父視圖需要計算佈局時調用onMeasure,而當特定視圖的佈局更改時調用onLayoutChange。 –