我想創建一個toast消息以在android中顯示,但是我不斷收到錯誤,這是與上下文有關的。如何在android中創建敬酒
我不是很瞭解上下文以及爲什麼會出現此錯誤。我的代碼如下,如果任何人都可以解釋如何解決這個問題,並展示一個很棒的例子。
public void drawPlayer(Canvas canvas){
int width = canvas.getWidth();
if(x > (width/2) + (rectSide/2)){
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
x = thePlayer.across;
y = thePlayer.upDown;
canvas.drawCircle(x, y, 40, green);
//canvas.drawBitmap(player, x, y, null);
}
public boolean onTouchEvent(MotionEvent ev) {
int height = this.getResources().getDisplayMetrics().heightPixels;
int width = this.getResources().getDisplayMetrics().widthPixels;
int leftSide = width/4;
int rightSide = width - (width/4);
if(ev.getAction() == MotionEvent.ACTION_DOWN) {
// the new image position became where you touched
x = ev.getX();
y = ev.getY();
if(x > rightSide){
thePlayer.right();
///theCrate.right();
}
if(x < leftSide){
thePlayer.left();
//theCrate.left();
}
if(x > leftSide && x < rightSide && y < height/2){
thePlayer.up();
//theCrate.up();
}
if(x > leftSide && x < rightSide && y > height/2){
thePlayer.down();
}
Draw.this.invalidate();
// redraw the image at the new position
}
return true;
}
public void drawGrid(Canvas canvas) {
int width = canvas.getWidth();
int height = canvas.getHeight();
float startX = (width/2) - (rectSide/2);
float stopX = (width/2) + (rectSide/2);
float startY = (height/2) - (rectSide/2);
float stopY = (height/2) + (rectSide/2);
for (int i = 0; i < 1100; i += 100) {
float newY = startY + i;
canvas.drawLine(startX, newY, stopX, newY, green);
}
for (int i = 0; i < 1100; i += 100) {
float newX = startX + i;
canvas.drawLine(newX, startY, newX, stopY, green);
}
}
public void drawPlayer(Canvas canvas){
int width = canvas.getWidth();
x = thePlayer.across;
y = thePlayer.upDown;
if(x > (width/2) + (rectSide/2)){
Toast.makeText(theContext.getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
canvas.drawCircle(x, y, 40, green);
//canvas.drawBitmap(player, x, y, null);
}
/*public void drawCrate(Canvas canvas){
x = theCrate.acrossCrate;
y = theCrate.upDownCrate;
canvas.drawBitmap(crate, x, y, null);
}*/
public void drawCrate(Canvas canvas){
if (thePlayer.across == theCrate.acrossCrate & thePlayer.upDown == theCrate.upDownCrate) {
theCrate.right();
xCrate = theCrate.acrossCrate;
yCrate = theCrate.upDownCrate;
}
else{
xCrate = theCrate.acrossCrate;
yCrate = theCrate.upDownCrate;
}
canvas.drawCircle(xCrate, yCrate, 40, black);
}
@Override
public void onDraw(Canvas canvas) {
int width = canvas.getWidth();
int height = canvas.getHeight();
canvas.drawRect(0,0,width/4,height,red);
canvas.drawRect((width - (width/4)),0,width,height,red);
canvas.drawRect(width/4,0,(width - (width/4)), height/2, blue);
canvas.drawRect(width/4,height/2,(width - (width/4)),height,blue);
drawGrid(canvas);
drawPlayer(canvas);
drawCrate(canvas);
}
}
發表您的錯誤的logcat –
getApplicationContext是正當紅的 – Phill
是否無效drawPlayer(帆布油畫)位於內內部課堂? –