我正在尝试将上下文从一个类传递到另一个类..请告诉我,我在做错了..
Draw.java
public class Draw extends View{
private Context context;
private Paint paint = null;
private Point start,end;
public Draw(Context check){
super(check);
paint();
}
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
canvas.drawRect(60,60,120,120,paint);
Check check = new Check(context.getApplicationContext());
check.update();
}
public void paint(){
paint= new Paint();
paint.setColor(Color.YELLOW);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
}
}
Check.java
public class Check {
private static Check check = null;
private Context context;
public Check(Context context){
this.context = context;
}
void update() {
Toast.makeText(context, "Context Received", Toast.LENGTH_LONG).show();
}
}
RectangleActivity.java
public class RectangleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
Context context;
super.onCreate(savedInstanceState);
Draw draw = new Draw(this);
setContentView(draw);
}
}
请帮帮我..我已经坚持这个问题好几天了......
答案 0 :(得分:3)
this.context = context;
否则当你到达 p>时,你会有一个null
context.getApplicationContext()
这也有点不必要,它足以传递context
。
答案 1 :(得分:1)
在构造函数中初始化上下文变量。或者使用this.getContext();而不是视图类中的上下文。