什么时候应根据其尺寸绘制自定义布局

问题描述:

我正在创建新的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开头?

只是检查的文档。还有就是在测量部分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

您可以使用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。 –