Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

為移植到 Android 平台的 Cocos2d-x 專案加入 XML 佈局檔(圖文)

編輯:關於 Android 程式設計

把 Cocos2d-x 專案移植到 Android 之後,常會需要在其 Activity 上疊加原生控制項,這時候就得靠 XML 佈局檔。以下記錄完整流程。

一、新增佈局檔 main.xml

內容如下,用 RelativeLayout 包住一個預留給 OpenGL 檢視的容器:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/gameviewLay"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

二、在 Java 檔案中載入佈局

接著在 Activity 裡覆寫 setCocosView,把 GL 檢視塞進剛才預留的容器中:

@Override
public void setCocosView(Cocos2dxGLSurfaceView mGLSurfaceView){
    setContentView(R.layout.main);
    RelativeLayout framelayout = (RelativeLayout) findViewById(R.id.gameviewLay);
    framelayout.addView(mGLSurfaceView);

    System.out.println("txc:setCocosView--初始化");
}

三、處理編譯錯誤

這時可能會出現「找不到可覆寫的父類方法」的錯誤,因為原本的 Cocos2dxActivity 並沒有這個方法。

(1)在提示視窗中選擇第一項,讓 IDE 於 Cocos2dxActivity 中建立 setCocosView():

(2)把原本 init() 中的內容整段搬到 setCocosView() 裡。

(3)在 init() 中改為呼叫 setCocosView():

// Cocos2dxGLSurfaceView
this.mGLSurfaceView = this.onCreateView();

// 在模擬器上切換為支援的 OpenGL(ARGB888)模式
// if (isAndroidEmulator())
//     this.mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0);

this.mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer());
setCocosView(mGLSurfaceView);

(4)回到原本的 Java 檔案確認,錯誤應該都消失了。

四、編譯執行驗證

執行成功,OpenGL 檢視已經被正確掛載到 XML 佈局指定的位置上,後續就能自由在它周圍加上原生控制項了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved