Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 開發基礎:建立對話框視窗

編輯:初階開發

在 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 來加入所需控件。

第二步:建立 About 類別

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 類別。

第四步:在 Manifest 中宣告(最關鍵)

別忘了在 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 會更合適。

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