java不能在类中使用上下文?
我目前正试图使用ContextCompact.getColor()
将我的颜色资源xml中的颜色输入到我的应用程序中,但由于某些原因,我无法传递单一版本的上下文
我使用一个类作为处理程序,所以我不试图从活动中传入。在我的活动中,我可以使用它们,但在我的课堂上,我不能传递getActivityContext()
{
此外,我正在向画布添加颜色,因此无法在xml中添加颜色
canvas.drawColor(Color.BLACK);
是我目前被迫使用的。我想用xml中的颜色替换它。(我正在尝试设置画布的背景)
我的课程的完整代码:(我把这个应用程序做成一个“笔记”应用程序,这样我就可以在将来的项目中回顾它,从而得到所有的评论)
public class GameHandling {
private SurfaceHolder holder;
private Resources resources;
private int screenWidth;
private int screenHeight;
private Ball ball;
private Bat player;
private Bat opponent;
public GameHandling(int width, int height, SurfaceHolder holder, Resources resources){
this.holder = holder;
this.resources = resources;
this.screenWidth = width;
this.screenHeight = height;
this.ball = new Ball(screenWidth, screenHeight, 400, 400);
this.player = new Bat(screenWidth, screenHeight, 0, 0, Bat.Position.LEFT);
this.opponent = new Bat(screenWidth, screenHeight, 0, 0, Bat.Position.RIGHT);
}
// setting the ball images to be drawn
public void inIt(){
Bitmap ballShadow = BitmapFactory.decodeResource(resources, R.mipmap.grey_dot);
Bitmap ballImage = BitmapFactory.decodeResource(resources, R.mipmap.red_dot);
Bitmap batPlayer = BitmapFactory.decodeResource(resources, R.mipmap.bat_player);
Bitmap batOpponent = BitmapFactory.decodeResource(resources, R.mipmap.bat_opponent);
ball.inIt(ballImage, ballShadow, 2, 0);
player.inIt(batPlayer, batPlayer, 0, 0);
opponent.inIt(batOpponent, batOpponent, 0, 0);
}
// calling Balls update method to update the ball
public void update(long elapsed){
ball.update(elapsed);
}
public void draw(){
Canvas canvas = holder.lockCanvas(); // Making a canvas object to draw on - .lockcanvas locks canvas
if(canvas != null) {
// draw in area between locking and unlocking
canvas.drawColor(Color.BLACK);
ball.draw(canvas);
player.draw(canvas);
opponent.draw(canvas);
holder.unlockCanvasAndPost(canvas); //-unlockcanvasandposts unlocks the canvas
}
}
}
# 1 楼答案
我想出了一个解决办法,用我想要的颜色创建了一个图像,然后用它作为应用程序的背景
然而,这仍然是一个解决办法,所以它不能解决我的问题
# 2 楼答案
将构造函数更改为此,并使用
ContextCompat.getColor(context,...
模式无论在何处创建这个类(活动/片段),都要传递上下文调用
getActivity()
或getApplicationContext()
new GameHandling( getActivity()/getApplicationContext(), ...)