Reputation: 23399
I'm trying to implement a custom view that is created by some data - specifically I am trying to create a revenue projection graph via a custom view.
The way i'm doing this is by having 10 data points, and drawing lines between each data point. (and then also drawing the X and Y axis lines).
I was thinking about creating a view that encapsulates the 10 coordinates, and draw them via the canvas in onDraw(). something like this:
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
}
}
but in order to do so, i think i need the width/height of the view, which isn't rendered until onDraw
.
is this the right approach? or am i even supposed to pass in a Points
list to the view? Or what's a better way to build this?
Upvotes: 0
Views: 92
Reputation: 23
You should use onMeasure() method which is called before onDraw() method, so you'll be able to get your view dimensions like this:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
}
You should avoid getting View dimensions directly in onDraw() method because it will be called many times a second
Upvotes: 1
Reputation: 2673
You should override the onMeasure()
method which will be called before onDraw()
.
https://developer.android.com/reference/android/view/View.html#onMeasure(int,%20int)
Measure the view and its content to determine the measured width and the measured height.
Upvotes: 2