我正在使用Gomoku的Android版本。對於Java來說,我是一個新手,對於Android來說更是如此。我正在關注一本名爲「Hello Android」的書,作者通過製作Sudoku遊戲來教授基本知識。我在鬆散地跟蹤它,忽略了我的Gomoku不需要的功能。然而,當新遊戲被按下時,一個新的觀點被提出,儘管這本書繼續下去,好像它應該有效,但是應該繪製的東西根本不會顯示出來。下面是與東西打交道的代碼:Android自定義視圖不顯示
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中,所以我認爲這個函數根本就不會被調用,我不明白爲什麼。