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

安卓第五天筆記:對話框(AlertDialog / 日期 / 進度)

編輯:關於 Android 開發

安卓第五天筆記 —— 對話框

1. 常見的對話框家族

AlertDialog:功能最豐富,可承載文字、列表、自訂版面。
ProgressDialog:進度對話框。
DatePickerDialog:日期選擇對話框。
TimePickerDialog:時間選擇對話框。

2. 用 AlertDialog 建立對話框的步驟

① 透過 AlertDialog.Builder 建立 builder 物件;
② 呼叫 setTitle 設定標題;
③ 呼叫 setIcon 設定圖示;
④ 設定內容;
⑤ 呼叫 create() 建立,再呼叫 show() 顯示。

設定內容的六種方法

setMessage() —— 內容為簡單文字。
setItems() —— 內容為簡單列表。
setSingleChoiceItems() —— 內容為單選列表項。
setMultiChoiceItems() —— 內容為多選列表項。
setAdapter() —— 內容為自訂的列表項。
setView() —— 內容為自訂 View。

3. 六種內容的實作

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context="com.itheima.alerdialog.MainActivity">

    <!-- 顯示結果的文本編輯框組件 -->
    <EditText
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:editable="false"/>

    <Button android:layout_width="match_parent" android:layout_height="wrap_content"
        android:text="簡單對話框" android:onClick="simple" />
    <Button android:layout_width="match_parent" android:layout_height="wrap_content"
        android:text="簡單列表項對話框" android:onClick="simpleList" />
    <Button android:layout_width="match_parent" android:layout_height="wrap_content"
        android:text="單選列表項對話框" android:onClick="singleChoice" />
    <Button android:layout_width="match_parent" android:layout_height="wrap_content"
        android:text="多選列表項對話框" android:onClick="multiChoice" />
    <Button android:layout_width="match_parent" android:layout_height="wrap_content"
        android:text="自定義列表項對話框" android:onClick="customList" />
    <Button android:layout_width="match_parent" android:layout_height="wrap_content"
        android:text="自定義View對話框" android:onClick="customView" />
</LinearLayout>

array_item.xml(自訂列表項的版面)

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tv">
</TextView>

login.xml(自訂 View 對話框的版面)

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/loginForm"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TableRow>
        <TextView android:layout_width="match_parent" android:layout_height="wrap_content"
            android:text="用戶名:" android:textSize="10pt"/>
        <EditText android:layout_width="match_parent" android:layout_height="wrap_content"
            android:hint="請填寫登錄賬號" android:selectAllOnFocus="true"/>
    </TableRow>

    <TableRow>
        <TextView android:layout_width="match_parent" android:layout_height="wrap_content"
            android:text="密碼:" android:textSize="10pt"/>
        <EditText android:layout_width="match_parent" android:layout_height="wrap_content"
            android:hint="請填寫密碼" android:password="true"/>
    </TableRow>

    <TableRow>
        <TextView android:layout_width="match_parent" android:layout_height="wrap_content"
            android:text="電話號碼:" android:textSize="10pt"/>
        <EditText android:layout_width="match_parent" android:layout_height="wrap_content"
            android:hint="請填寫您的電話號碼" android:selectAllOnFocus="true"
            android:phoneNumber="true"/>
    </TableRow>
</TableLayout>

MainActivity

/**
 * 對話框
 * 1. 使用 AlertDialog.Builder 建立 builder 物件
 * 2. setTitle
 * 3. setIcon
 * 4. 設定內容
 * 5. create() 建立,再 show() 顯示
 */
public class MainActivity extends AppCompatActivity {

    private TextView show;
    private String[] items = { "瘋狂Java講義", "瘋狂Ajax講義",
            "輕量級Java EE企業應用實戰", "瘋狂Android講義" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show = (TextView) findViewById(R.id.show);
    }

    /** 簡單對話框 */
    public void simple(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("簡單對話框")
                .setIcon(R.drawable.tools)
                .setMessage("對話框測試內容\n第二行內容");
        setPositiveButton(builder);
        setNegativeButton(builder);
        builder.create().show();
    }

    /** 簡單列表項對話框 */
    public void simpleList(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("簡單列表對話框")
                .setIcon(R.drawable.tools)
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        show.setText("您選中了<<" + items[which] + ">>");
                    }
                });
        setPositiveButton(builder);
        setNegativeButton(builder);
        builder.create().show();
    }

    /** 單選列表項對話框 */
    public void singleChoice(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("單選列表項對話框")
                .setIcon(R.drawable.tools)
                .setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        show.setText("您選中了<<" + items[which] + ">>");
                    }
                });
        setPositiveButton(builder);
        setNegativeButton(builder);
        builder.create().show();
    }

    /** 多選列表項對話框 */
    public void multiChoice(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("多選列表項對話框")
                .setIcon(R.drawable.tools)
                .setMultiChoiceItems(items, new boolean[]{true, false, true, false},
                        new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        show.setText("您選擇了<<" + items[which] + ">>");
                    }
                });
        setPositiveButton(builder);
        setNegativeButton(builder);
        builder.create().show();
    }

    /** 自定義列表項對話框 */
    public void customList(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("自定義列表項對話框")
                .setIcon(R.drawable.tools)
                .setAdapter(new ArrayAdapter<String>(this, R.layout.array_item, items),
                        new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        show.setText("您選擇了<<" + items[which] + ">>");
                    }
                });
        setPositiveButton(builder);
        setNegativeButton(builder);
        builder.create().show();
    }

    /** 自定義 View 對話框 */
    public void customView(View v) {
        // 透過 LayoutInflater 取得 View 物件
        TableLayout loginForm = (TableLayout) getLayoutInflater().inflate(R.layout.login, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("自定義View對話框")
                .setIcon(R.drawable.tools)
                .setView(loginForm);
        setPositiveButton(builder);
        setNegativeButton(builder);
        builder.create().show();
    }

    /** 設定確定按鍵 */
    private AlertDialog.Builder setPositiveButton(AlertDialog.Builder builder) {
        return builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                show.setText("單擊了[ 確定 ] 按鍵");
            }
        });
    }

    /** 設定取消按鍵 */
    private AlertDialog.Builder setNegativeButton(AlertDialog.Builder builder) {
        return builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                show.setText("單擊了[ 取消 ] 按鍵");
            }
        });
    }
}

4. 日期與時間對話框

建立步驟:

① new DatePickerDialog 或 new TimePickerDialog;
② 配置建構式,最重要的參數是監聽器;
③ 呼叫 show()。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.itheima.datepickerdialogandtimepickerdialog.MainActivity">

    <TextView
        android:id="@+id/show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"/>

    <Button android:layout_width="match_parent" android:layout_height="wrap_content"
        android:onClick="showDate" android:text="日期對話框"/>
    <Button android:layout_width="match_parent" android:layout_height="wrap_content"
        android:onClick="showTime" android:text="時間對話框"/>
</LinearLayout>
/**
 * 建立日期與時間對話框
 * 1. new DatePickerDialog 或 new TimePickerDialog
 * 2. 配置建構式,最重要的為監聽器
 * 3. show
 */
public class MainActivity extends AppCompatActivity {

    private TextView tv_show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_show = (TextView) findViewById(R.id.show);
    }

    /** 顯示日期對話框 */
    public void showDate(View v) {
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                tv_show.setText("您選擇" + year + "年" + monthOfYear + "月" + dayOfMonth + "日");
            }
        },
        // 設定初始日期
        c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)
        ).show();
    }

    /** 顯示時間對話框 */
    public void showTime(View v) {
        Calendar c = Calendar.getInstance();
        new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                tv_show.setText("您選擇" + hourOfDay + "時" + minute + "分");
            }
        },
        // 設定初始時間,最後參數 true 表示使用 24 小時制
        c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true
        ).show();
    }
}

注意: DatePickerDialog 回傳的 monthOfYear 是從 0 開始計算的,若要顯示直覺的月份,記得 +1。

5. 進度條對話框

5.1 建立簡單的進度對話框

直接呼叫 ProgressDialog 提供的靜態 show() 方法即可。

5.2 建立有進度條的對話框

先建立物件,再依序設定:
setTitle 設定標題;
setMessage 設定訊息;
setMax 設定進度條最大值;
setProgress 設定目前進度;
setProgressStyle 設定進度條風格(STY​​LE_HORIZONTAL 為水平,預設為圓環)。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.itheima.progressdialog.MainActivity">

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:onClick="showSpinnr" android:text="普通的環形對話框"/>
    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:onClick="showIndeterMinate" android:text="不顯示進度對話框"/>
    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:onClick="showProgress" android:text="顯示進度對話框"/>
</LinearLayout>
/**
 * 進度條對話框
 * 1. 建立 ProgressDialog 物件
 * 2. 設定標題與內容 setTitle, setMessage
 * 3. 設定進度條是否可見 setIndeterminate —— true 為不可見
 * 4. 設定風格 setProgressStyle
 * 5. 呼叫 show 方法
 */
public class MainActivity extends AppCompatActivity {

    final static int MAX_PROGRESS = 100;
    // 用陣列模擬耗時任務
    private int[] data = new int[50];
    // 對話框 2、3
    private ProgressDialog p1, p2;
    // 完成的百分比
    private int progressStatus = 0;
    private int hasdata = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                p2.setProgress(progressStatus);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * 普通的環形對話框
     * indeterminate 為 false 表示顯示進度;cancelable 表示可點擊取消
     */
    public void showSpinnr(View v) {
        ProgressDialog.show(this, "任務執行中", "請稍後", false, true);
    }

    /** 不顯示進度的對話框 */
    public void showIndeterMinate(View v) {
        p1 = new ProgressDialog(MainActivity.this);
        p1.setTitle("任務執行中");
        p1.setMessage("任務執行中,請稍後.........敬請期待");
        p1.setCancelable(true);        // 可點擊取消
        p1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        p1.setIndeterminate(true);     // 進度條不顯示
        p1.show();
    }

    /** 顯示進度對話框 */
    public void showProgress(View v) {
        progressStatus = 0;
        hasdata = 0;

        p2 = new ProgressDialog(MainActivity.this);
        p2.setMax(MAX_PROGRESS);
        p2.setTitle("任務完成百分比");
        p2.setMessage("耗時任務的完成百分比");
        p2.setCancelable(false);       // 不可點擊取消
        p2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        p2.setIndeterminate(false);
        p2.show();

        // 啟動耗時任務
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (progressStatus < MAX_PROGRESS) {
                    progressStatus = MAX_PROGRESS * doWork() / data.length;
                    handler.sendEmptyMessage(0x123);
                }
                if (progressStatus >= MAX_PROGRESS) {
                    p2.dismiss();
                }
            }
        }).start();
    }

    /** 模擬一個耗時操作 */
    private int doWork() {
        data[hasdata++] = (int) (Math.random() * 100);
        SystemClock.sleep(100);
        return hasdata;
    }
}

本節重點回顧

AlertDialog 的核心在於 Builder 的串接式寫法,而六種內容設定方法則對應不同情境:純文字提示用 setMessage,選項不多用 setItems,需要限定單選或多選時分別用 setSingleChoiceItems 與 setMultiChoiceItems,版面較複雜時再改用 setAdapter 或 setView。

另外要提醒:ProgressDialog 在 API 26 已被標示為不建議使用,官方建議改用 Toolbar 搭配 ProgressBar 或自訂的 Loading 元件。不過它的觀念——尤其是「耗時任務必須放在子執行緒、再透過 Handler 更新進度」這套做法——至今仍然是標準模式。

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