Android簡明開發教程八說明了程式需要實現的功能,就可以建立Android項目了。請參見Android簡明開發教程三:第一個應 用Hello World ,建立一個新項目AndroidGraphics2DTutorial。今天先介紹建立的程式的架構。然後再項目添加如下類定義:
添加第三方庫檔案
AndroidGraphics2DTutorial調用了引路蜂二維圖形庫,因此需要在項目中添加第三方庫引用(libgisengine.jar),開啟 Android屬性視窗,添加External JARs。把libgisengine.jar 添加到項目中,引路蜂二維圖形庫是引路蜂地圖開發包的一部分 。添加庫引用可以參見 Android引路蜂地圖開發樣本:基本知識。
類說明,下表列出了項目中定義的類的簡要說明:
| 類 |
說明 |
| AndroidGraphics2DApplication |
應用程式類,為Application子類 |
| AndroidGraphics2DTutorial |
主Activity,為ListActivity子類,用於列出其它樣本。 |
| GuidebeeGraphics2DSurfaceView |
SurfaceView子類用於顯示圖形 |
| GuidebeeGraphics2DView |
View子類用於顯示圖形,與GuidebeeGraphics2DSurfaceView 功能一樣,在程式中可以互換 。 |
| SharedGraphics2DInstance |
定義了共用類對象,主要包含Graphics2D |
| Graphics2DActivity |
Activity子類,為所有樣本基類,定義一些所有樣本共用的類變數和函數。 |
| Bezier,Brush,Colors,Font,Image,Path,Pen,Shape,Transform |
為Graphics2DActivity的子類,為二維圖形示範各個功能 |
AndroidGraphics2DApplication ,其實在一般的Android應用中,無需定義Application的衍生類別,比如在Hello World中就 沒有定義,當是如果想在多個Activity中共用變數,或是想初始化一些全域變數,可以定義Application的衍生類別,然後可以在 Activity或Service中調用 getApplication() 或 getApplicationContext()來取得Application 對象,可以訪問定義在 Application中的一些共用變數。在這個例子中AndroidGraphics2DApplication嚴格些也可不定義,為了說明問題,還是定義了 用來初始化Graphics2D執行個體,Graphics2D執行個體可以被所有樣本Activity,如Colors,Font訪問。如果定義了Application的派生 類,就需要在AndroidManifest.xml中說明Application衍生類別的位置。
<manifest xmlns:android=”http://schemas.android.com/apk/res/android ”
package=”com.pstreets.graphics2d ”
android:versionCode=”1″
android:versionName=”1.0″>
<application android:name=”AndroidGraphics2DApplication ”
android:icon=”@drawable/icon” android:label=”@string/app_name”>
<activity android:name=”.AndroidGraphics2DTutorial”
android:label=”@string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
…
</application>
<uses-sdk android:minSdkVersion=”4″ />
</manifest>
Application 可以重載 onCreate()和 onTerminate() ,onCreate()在應用啟動時執行一次,onTerminate()在應用推出執行 一次。AndroidGraphics2DApplication 的onCreate() 中初始化Graphics2D執行個體:
public void onCreate() {
SharedGraphics2DInstance.graphics2d=
new Graphics2D(SharedGraphics2DInstance.CANVAS_WIDTH,
SharedGraphics2DInstance.CANVAS_HEIGHT);
}
AndroidGraphics2DTutorial 為ListActivity子類,直接從AndroidManifest.xml中讀取Intent-Filter Catetory 為 com.pstreets.graphics2d.SAMPLE_CODE 的所有Activity。
private static final String SAMPLE_CATEGORY= "com.pstreets.graphics2d.SAMPLE_CODE" ;
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null );
mainIntent.addCategory(SAMPLE_CATEGORY);
...