如何从android中的另一个类调用一个方法?

时间:2015-06-24 08:42:33

标签: java android

我在android studio中有两个类用于游戏。 Crate类和玩家类。我想知道:如何在crate类中调用播放器类?我试图通过Player thePlayer = new Player(getContext());但这只是让我为get上下文部分给出错误。

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;
}

2 个答案:

答案 0 :(得分:2)

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

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);

}

答案 1 :(得分:0)

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

public Crate(Context context) {
thePlayer = new Player(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;
}