[英]How to call a method from another class in android?
我在android studio中有兩個課程可以玩。 板條箱類和玩家類。 我想知道:如何在板條箱類中調用播放器類? 我正在嘗試通過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);
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.