gpt4 book ai didi

java - 如何在android中调用另一个类的方法?

转载 作者:行者123 更新时间:2023-12-02 04:34:22 28 4
gpt4 key购买 nike

我在 android studio 中有两个游戏类(class)。 crate 类和玩家类。我想知道:我如何在 crate 类中调用玩家类?我试图通过 Player thePlayer = new Player(getContext()); 来做到这一点但这只会不断给我获取上下文部分带来错误。

public class Crate {
public static int acrossCrate;
public int upDownCrate;
Player thePlayer = new Player(getContext()); //<--GIVES ERROR

public Crate(Context context) {

int rect = 1000;
int height = context.getResources().getDisplayMetrics().heightPixels;
int width = context.getResources().getDisplayMetrics().widthPixels;

int startPosX = (width/2)-(rect/2);
int startPosY = (height/2)-(rect/2);

acrossCrate = startPosX +300;
upDownCrate = startPosY +300;

}


public class Player {
public static int across;
public int upDown;
int boardWidth;
int boardHeight;
int startPosX;
int startPosY;
int stopPosX;
int stopPosY;

public Player(Context context) {

int rect = 1000;
boardHeight = context.getResources().getDisplayMetrics().heightPixels;
boardWidth = context.getResources().getDisplayMetrics().widthPixels;

startPosX = (boardWidth/2)-(rect/2);
startPosY = (boardHeight/2)-(rect/2);
stopPosX = (boardWidth/2)+(rect/2);
stopPosY = (boardHeight/2)+(rect/2);

across = startPosX+500;
upDown = startPosY+500;
}

最佳答案

将代码的第一部分转换为以下部分:

public class Crate {
public static int acrossCrate;
public int upDownCrate;
Player thePlayer;

public Crate(Context context) {

int rect = 1000;
int height = context.getResources().getDisplayMetrics().heightPixels;
int width = context.getResources().getDisplayMetrics().widthPixels;

int startPosX = (width/2)-(rect/2);
int startPosY = (height/2)-(rect/2);

acrossCrate = startPosX +300;
upDownCrate = startPosY +300;

//define your player here
thePlayer = new Player(context);

}

关于java - 如何在android中调用另一个类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31021777/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com