tags:

views:

46

answers:

2

subclass a View and then override the onDraw(Canvas) method

import android.app.Activity; import android.os.Bundle; import android.view.View; import android.graphics.Canvas;

  public class POCII extends Activity {

myView mv = new myView(this);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(mv);
}

}

class myView extends View{

public myView(Context context){
    super(context);
}
@Override
public void onDraw(Canvas canvas) {
    Paint paint = new Paint();

    canvas.drawRect(0,0,100,100, paint);
}

}

My question is, when I'm instantiating the myView in the Activity, why is it necessary to pass the context and why is it required to pass the context to the View's constructor? What is the significance??

A: 

The View superclass requires the Context in which it is running in order to access certain resources such as the current theme, etc.

Andy Zhang
A: 

The view needs to know about the current application context to be able to access it. Here you got some info about what is the context about: http://developer.android.com/reference/android/content/Context.html

Moss