我正在开发一个Android版的Gomoku。我对Java很新,对Android也是如此。我正在关注一本名为“Hello Android”的书,其中作者通过制作数独游戏来教授基础知识。我松散地跟着它,遗漏了我的Gomoku不需要的功能。然而,当新游戏被按下时会产生一个新的视图,尽管这本书仍在继续,好像它应该正常工作,应该绘制的内容根本不适合我。以下是处理这些内容的代码:
Mainactivity.java:
private void startGame() {
Log.d(TAG, "Clicked New Game");
Intent intent = new Intent(this, Game.class);
startActivity(intent);
}
Game.java:
public class Game extends Activity {
private static final String TAG = "Game";
private int board[] = new int[10 * 10];
private GameView gameView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Game.onCreate called");
gameView = new GameView(this);
gameView.requestFocus();
Log.d(TAG, "Game.onCreate finished");
}
}
GameView.java:
public class GameView extends View {
private static final String TAG = "Game";
private float width; //Width of one tile
private float height; //Height of one tile
private final Game game;
Paint background = new Paint();
Paint dark = new Paint();
Paint light = new Paint();
Paint hilite = new Paint();
public GameView(Context context) {
super(context);
this.game = (Game) context;
setFocusable(true);
setFocusableInTouchMode(true);
Log.d(TAG, "GameView finished");
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width = w / 10f;
height = h /10f;
Log.d(TAG, "onSizeChanged: width " + width + ", height " + height);
}
@Override
protected void onDraw(Canvas canvas) {
//Draw the background
background.setColor(getResources().getColor(R.color.background));
canvas.drawRect(0, 0, getWidth(), getHeight(), background);
//Draw the board
//Define colors for grid lines
dark.setColor(getResources().getColor(Color.DKGRAY));
light.setColor(getResources().getColor(Color.LTGRAY));
hilite.setColor(getResources().getColor(Color.WHITE));
for (int i = 0; i < 10; i++) {
Log.d(TAG, "Drawing...");
canvas.drawLine(0, i * height - 1, getWidth(), i * height - 1, light);
canvas.drawLine(0, i * width - 1, getHeight(), i * width - 1, light);
canvas.drawLine(0, i * height, getWidth(), i * height, hilite);
canvas.drawLine(0, i * width, getHeight(), i * width, hilite);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1, dark);
canvas.drawLine(0, i * width + 1, getHeight(), i * width + 1, dark);
}
}
}
我尝试将作者的代码与我的代码进行比较,除非我没有实现功能,否则代码似乎是匹配的。 但是,Log.d(TAG,“onSizeChanged:width”+ width +“,height”+ height);没有出现在LogCat中所以我认为这个函数根本就没有被调用过,我不明白为什么。
答案 0 :(得分:0)
您需要将视图设置为setContentView(gameView)
onCreate
活动中Game
的活动。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Game.onCreate called");
gameView = new GameView(this);
setContentView(gameView); // missing
...//rest of the code
答案 1 :(得分:0)
您只需创建GameView的实例,但不要将其添加到您的活动中。通过使用
执行此操作setContentView(gameView);
你的onCreate方法中的。