我对Android很新,我需要帮助。
我有一个GameActivity类,我将setContentView设置为GameView类。 我想从GameActivity类访问位于GameView类中的变量。
这可能吗?
public class GameActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
View gameview = new GameView(this);
setContentView(gameview);
}
}
这是我的GameView课程
public class GameView extends View {
private static final String TAG = null; // for log.e
private Ball ball1; // ball1
private GameContainer gameContainer; // frame for the game
private Racket racket; // controller
int viewWidth = 0; // width onchange
int viewHeight = 0; // height onchange
private Score score;
// constructor
public GameView(Context context) {
super(context);
ball1 = new Ball(Color.GREEN, 24, 10, 2); // colour, radius,speedx, speedy
ball1.setBallLocation(10, 5); // x, y of ball
gameContainer = new GameContainer(Color.GRAY);
racket = new Racket(Color.BLACK);
score = new Score(Color.WHITE);
}
@Override
public void onDraw(Canvas canvas){
gameContainer.container(1, 2, 100, 100);
gameContainer.display(canvas);
ball1.drawBall(canvas);
ball1.moveBall(gameContainer);
// check the ball if it is out display the alert box
if (ball1.getEndGame()){
Log.e(TAG, "END of game");
}
}
}
答案 0 :(得分:0)
Plain Old Java
约定应该有效。
为您需要访问的变量添加getter / setter方法,并使用它们来获取值。
public int getHeight(){
return viewHeight;
}
这不起作用吗
答案 1 :(得分:0)
要直接访问某些属性,首先将其声明为public:
public int viewWidth = 0;
第二,只需称呼它:
gameview.viewWidth = ...