绘制自定义视图的正确方法?

时间:2018-10-17 08:08:31

标签: android refactoring android-custom-view

我正在尝试实现由某些数据创建的自定义视图-具体来说,我正在尝试通过自定义视图创建收入预测图。

我这样做的方法是拥有10个数据点,并在每个数据点之间画线。 (然后还绘制X和Y轴线)。

我正在考虑创建一个封装10个坐标的视图,并通过onDraw()中的画布绘制它们。像这样的东西:

class RevView extends View {
    private List<Point> mPoints;
    public void configurePoints(float[] revenues) { 
        // convert revenues to points on the graph.
    }
    // ... constructor... etc.
    protected void onDraw(Canvas canvas) {
        // use canvas.drawLine to draw line between the points
    }
}

但是为了做到这一点,我认为我需要视图的宽度/高度,直到onDraw才会呈现。

这是正确的方法吗?还是我应该将Points列表传递给视图?还是有什么更好的方法来构建它?

2 个答案:

答案 0 :(得分:2)

您应该覆盖onMeasure()之前将调用的onDraw()方法。

https://developer.android.com/reference/android/view/View.html#onMeasure(int,%20int)

  

测量视图及其内容,以确定测量的宽度和测量的高度。

答案 1 :(得分:1)

您应该使用 onMeasure()方法,该方法在 onDraw()方法之前被调用,这样您将能够获得如下视图尺寸:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = measureWidth(widthMeasureSpec);
    int height = measureHeight(heightMeasureSpec);
}

您应该避免直接在 onDraw()方法中获取View尺寸,因为它会在一秒钟内被多次调用

相关问题