編輯:初階開發
在 Android 中做一個「關於」對話框其實很簡單,關鍵是善用 Activity 搭配 Dialog 主題。以下用建立 About 視窗為例,拆成四個步驟。
在 res/layout 下新增 about.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="@+id/TextView01"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/about_title"></TextView>
<TextView android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/about_content"></TextView>
</LinearLayout>
在 Eclipse 中可以用視覺化編輯器或直接改 XML 來加入所需控件。
Android 的視窗都由 Activity 管理,因此從 Activity 派生一個類別,並在 onCreate 中關聯剛才的版面:
public class About extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
}
}
做到這裡,對話框的內容其實已經完成了,剩下的是怎麼把它叫出來。
以下範例在按鈕點擊時建立一個 Intent,把 About 視窗叫出來:
public void onClick(View v) {
switch (v.getId()) {
case R.id.Button03:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
}
}
Intent 的第二個參數就是關聯的 About 類別。
別忘了在 AndroidManifest.xml 中加上這個 Activity,否則執行時會找不到而報錯。這裡的重點是加上 android:theme:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.HelloWorld"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".HelloWorld"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".About"
android:label="@string/about_title"
android:theme="@android:style/Theme.Dialog">
</activity>
</application>
<uses-sdk android:minSdkVersion="7" />
</manifest>
到這裡,整個對話框的建立與顯示流程就完成了。
如果對顯示出來的樣子不夠滿意,Android 提供了不少預設主題可以套用。只要指定一個主題,就能很容易地改變對話框的外觀,例如上面使用的 @android:style/Theme.Dialog。其他常見選項還有 Theme.Dialog.NoFrame(不帶邊框)等,可以逐一試看看哪個最合適。
補充一點:這種「用 Activity 加 Dialog 主題」的做法,優點是可以直接沿用 Activity 的生命週期管理;缺點是它本質上仍是一個獨立 Activity,會進入返回堆疊。若只是想要一個輕量的提示框,改用 DialogFragment 或直接建立 AlertDialog 會更合適。
用 OpenGL ES 在 Android 上畫一個旋轉的圓
這是我在 Android 上用 OpenGL ES 畫的第一個圖形,Render 的覆寫部分參考了其他同學的程式碼。以下完整程式碼可直接運行。 public clas
Android APK 軟體漢化教學(二):從 arsc 到 classes.dex
本文承接上一篇,說明 APK 漢化的完整流程,分成四個部分:resources.arsc、XML 檔、classes.dex,以及最後的簽名。全程使用 androidRe
Android 開發實作:SeekBar 與 RatingBar 的用法
SeekBar:可拖動的進度條 先在版面檔裡放進控制項: <SeekBar android:id=@+id/mySeekBar android:la
Android ApiDemo 圖形與視圖(五):Spinner、Tab 頁籤與 WebView 入門
本篇是 ApiDemo「Graphics and Views」系列筆記的收尾,涵蓋第 70 到 76 號範例:下拉選單 Spinner、三種不同風格的 Tab 實作、帶切