0

I have a Class called LineGraphView which is a subclass of View. I want to be able to pass some data to this view so that it can then draw accordingly in its onDraw() method.

Analysis Fragment (Where the view is referenced and method is called from)

LineGraphView altitudeGraph;
LineGraphView speedGraph;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
    super.onCreateView(inflater, group, saved);

    View view = inflater.inflate(R.layout.analysisfrag, group, false);
    this.altitudeGraph = (LineGraphView) view.findViewById(R.id.linegraph_Altitude);
    this.speedGraph = (LineGraphView) view.findViewById(R.id.linegraph_Speed);

    return view;
}

My question is, if I then want to be able to access that views width and height attributes using getWidth() and getHeight(), when am I able to do so because so far all thats being returned is 0.

Do I need to create a listener which lets the LineGraphView's parent know its ready to be accessed?

Thanks in advance.

StuStirling
  • 15,601
  • 23
  • 93
  • 150

2 Answers2

1

If you're already creating your own custom view, I would just add some private variables with getters/setters for the information you need to pass. From there, just handle the drawing in your onDraw() method -- from there, you can get your View's width and height (or just the Canvas width and height, which might be the same values).

Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
  • The thing is I need to send data from my fragment (which is where my view is inflated from). When can I do that? – StuStirling Jul 03 '12 at 14:46
  • If you've got public setters for the data, you can send it at any time. I may be misunderstanding the question, but it shouldn't matter when you send it, just make sure in your setter that you invalidate and/or requestLayout on the view to make sure it refreshes. Alternately, if you wanted to take the listener route, there is an OnPreDrawListener that you could use. http://developer.android.com/reference/android/view/ViewTreeObserver.OnPreDrawListener.html – Kevin Coppock Jul 03 '12 at 14:56
  • I managed to get it working the first way you said. Thanks very much for your help – StuStirling Jul 03 '12 at 15:38
0

The answer is here: https://stackoverflow.com/a/3594216/969325 Basically you are calling getWidth/height too early (during onCreate). I believe you could use a handler to get it after onCreate. You could also try this: https://stackoverflow.com/a/10118459/969325 (using onWindowFocusChanged).

Community
  • 1
  • 1
Warpzit
  • 27,966
  • 19
  • 103
  • 155