When you say CustView custView = (CustView)findViewById(R.id.cust); you are trying to get a handle on the CustView object that was inflated(created) by parsing the layout XML file, when the View hierarchy was created. The constructor of the CustView will be invoked when you set contentView for the activity using the line: setContentView(R.layout.main);
When you say: CustView custView = new CustView (this); you are creating the a "new" view object in code and getting its reference in traditional Java-way.
This way you have more control on the object creation: you will be invoking a single arguement constructor of the view class. However, when the view is inflated from the layout XML a different constructor of the View will be called.(Probably the two arguement or the three arguement constructor). You can check this by writing a simple code.
Also, note that both the references will not be same. That is to say, if you have something like :
One more question,
I notice that if I will initialize any variable (for example Paint) in the CustView constructor he will be null when calling the onDraw function.
Why is that ?
Would it be better to initialize those variables only once in the constructor instead of using the onDraw ?
Few things to note first:
1. Though onDraw(Canvas) method is a callback which is called whenever you view is invalidated, it is nevertheless an instance method.
2. Instance methods can be called by the JVM or by the programmer only on some instance of class. This means that if onDraw() was called, the instance of your CustView WAS created.
If an instance of CustView was created then the constructor must have run. If the constructor has run your Paint object should have been initialized.
As already pointed out in my first post, different constructors of the view are called depending on how the view has been created. Please check if your constructor is being invoked. Usually, I put all my initialization code in one function and call this function from every constructor of the view.
If this is not the problem or doesnt help solve it, please post your code.
Joined: Sep 09, 2005
I didn’t initialize the variables via all constructors that’s way it was null
Thanks for the help
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com