在 OnClickListener 匿名內部類中創建 BallView:
kaishi.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// ...
myview = new BallView(this); // 錯誤:this 指向 OnClickListener 實例,而非 Activity
setContentView(myview);
}
});
編譯錯誤:BallView(Context) 需要 Context,但 this 是 OnClickListener。
使用外部類限定 this:
myview = new BallView(DazhuankuaiActivity.this); // 正確:指向 Activity 實例
kaishi.setOnClickListener(new View.OnClickListener() { // 接口用 View.OnClickListener
@Override
public void onClick(View v) {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
screenWidth = dm.widthPixels;
screenHeight = dm.heightPixels;
requestWindowFeature(Window.FEATURE_NO_TITLE); // 必須在 setContentView 前調用
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
myview = new BallView(DazhuankuaiActivity.this); // 關鍵修正
setContentView(myview);
}
});
原代碼將遊戲邏輯 (BallView) 與主 Activity 混在一個文件,且 BallView 靜態依賴 DazhuankuaiActivity.screenWidth,耦合度極高。建議重構:
BallView.java 獨立類,構造函數傳入 Context 和 尺寸參數。
public BallView(Context context, int screenWidth, int screenHeight) {
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
// ...
}
surfaceCreated 啟動線程,surfaceDestroyed 停止線程 (原代碼已基本正確)。BallView 覆寫 onTouchEvent 處理觸摸,或由 Activity 分發按鍵事件。static final 常量。| 錯誤代碼 | 問題 | 修正 |
|---|---|---|
new BallView(this) 在 OnClickListener 中 | this 是 Listener,非 Context | new BallView(OuterActivity.this) |
requestWindowFeature 在 setContentView 後 | 必須在 setContentView 前調用 | 移至 onCreate 最開頭或 setContentView 前 |
靜態訪問 DazhuankuaiActivity.screenWidth | 強耦合、難測試、記憶體洩漏風險 | 構造函數傳參或接口回調 |
匿名內部類中訪問外部 Activity 實例,**必須用 OuterClass.this**。遊戲開發中,視圖與邏輯解耦、生命周期正確管理、常量提取,是可維護代碼的基石。