不能在课堂上使用上下文



我当前正在尝试使用ContextCompact.getColor()从我的颜色资源xml中添加颜色xml,但由于某些原因,我无法传递单个版本的上下文。

我正在使用类作为处理程序,因此我不会试图从活动中传递。在我的活动中,我可以使用它们,但是在我的班级中,我不能传递getActivityContext() this等。我该怎么办?

另外,我将颜色添加到画布中,因此我无法在xml中添加颜色。

canvas.drawColor(Color.BLACK);

是我目前被迫使用的。我想用XML的颜色替换它。(我试图从本质上设置画布的背景)

我班级的完整代码:(我正在将此应用程序作为" Note"应用程序,以便我可以回顾一下以后的项目,因此所有评论)

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
        }

    }
}

将您的构造函数更改为此并使用ContextCompat.getColor(context,...模式。

无论您在哪里创建此类(活动/片段),都可以通过上下文来调用getActivity()getApplicationContext()

new GameHandling( getActivity()/getApplicationContext(), ...)

public GameHandling(Context context, int width, int height, SurfaceHolder holder, Resources resources){
    this.context = context;
    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);
}

我想到了一个解决方法,我用理想的颜色创建了一个图像,然后将其用作应用程序的背景。

但是它仍然是解决方法,因此它无法解决我的问题

最新更新