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

自訂 AlertDialog:打造帶圖示與可捲動說明的「關於」提示框

編輯:Android 開發實例

幾乎每個 App 都會有一頁「關於」或「使用說明」,內容通常包含版本號、作者、功能列表與專案連結。與其每次手寫 Dialog,不如繼承 AlertDialog 做一個專用的 HelpDialog,把版面配置、標題與按鈕一次處理乾淨,之後任何 Activity 只要 new 一下就能用。

這個做法的關鍵在於 setView():它允許你把任意 layout 塞進對話框的主體區域,於是原本只能放文字的提示框,瞬間變成可以承載捲動畫面的資訊頁。

HelpDialog 類別

import android.app.AlertDialog;

import android.content.Context;

import android.view.View;

import com.iwidsets.task.manager.R;

public class HelpDialog extends AlertDialog {

public HelpDialog(Context context) {

super(context);

final View view = getLayoutInflater().inflate(R.layout.help_dialog, null);

setButton(context.getText(R.string.close), (OnClickListener) null);

setIcon(R.drawable.icon);

setTitle("AndTask version:" + R.string.version);

setView(view);

}

}

幾行程式碼做了四件事:把 help_dialog 版面膨脹成 View、掛上一顆「關閉」按鈕(監聽器傳 null,因為關閉是 Dialog 的預設行為)、設定左上角圖示、把標題與版本字串拼起來。由於版本號寫在 strings.xml 裡,改版時只動資源檔就好。

說明文字資源

內容量多時建議直接放在 strings.xml,再用 basic 的 HTML 標籤做簡單排版:

<string name="help_dialog_text">

<i>Author: fonter.yang</i>

n

<i>

<a href="https://www.android.tgbus.com">Android教程 </a>

</i>

n

n

<i>AndTask - Android Task Manager</i>

n

This's an easy-to use task management software,it allows you to switch on or off running programs/apps/services.

n

n

<b>Feature</b>

n

1) Switch and Stop Tasks/Processes/Apps/Services

2) Shows Memory Info and Apps Info

3) Uninstall Apps

</string>

對話框版面

說明文字往往超過一頁,所以外層必須包 ScrollView,否則超出部分會被裁掉、連關閉都看不到內容:

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"

android:layout_height="wrap_content"

android:layout_width="fill_parent"

>

<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"

android:layout_height="fill_parent"

android:layout_width="fill_parent"

>

<TextView

android:layout_height="fill_parent"

android:layout_width="fill_parent"

android:padding="6dip"

android:text="@string/help_dialog_text"

/>

</ScrollView>

</FrameLayout>

最外層的 FrameLayout 是為了讓版面高度用 wrap_content 而不撐滿整個對話框,內層 ScrollView 負責承載過長的內容,TextView 的 6dip 內距則讓文字不會貼邊。三層結構各司其職,換成任何長度都不會破版。

最後提醒一點:早期專案常用 <a href> 呈現連結,但 TextView 只會把 URL 上色,點擊需要額外設定 MovementMethod 才會真的開啟瀏覽器。若要支援點擊,可在 HelpDialog 建構子中對該 TextView 呼叫 setMovementMethod(LinkMovementMethod.getInstance())。

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