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

DialogFragment 完整實戰:官方為什麼要你用它取代 Dialog

編輯:關於 Android 程式設計

一、DialogFragment 是什麼

DialogFragment 從 Android 3.0(API 13)開始引入,它本質上是一種特殊的 Fragment,用途是在 Activity 的內容之上疊出一個模態對話框。典型的應用場景包括警告提示、資料輸入、操作確認等等。

在它出現之前,我們要建構對話框通常直接 new 一個 AlertDialog 或 Dialog。但官方明確不建議直接建立 Dialog,原因就在下面幾節。

二、改用 DialogFragment 的好處

把對話框交給 DialogFragment 管理,最大的收益是生命週期變得可控。旋轉螢幕、按下返回鍵時,FragmentManager 會幫你把狀態留好,不會像裸 Dialog 那樣直接消失甚至讓 Activity 崩潰。

其次,DialogFragment 具備 Fragment 的一切能力,可以當成內嵌元件重複使用——同一顆 Fragment,在大螢幕上以浮動視窗呈現,在小螢幕上直接鋪滿嵌入 Activity,這件事只有 DialogFragment 做得到。

使用 DialogFragment 至少要覆寫 onCreateView 或 onCreateDialog 其中之一:前者用 XML 布局呈現對話框,後者用 AlertDialog 或 Dialog 建立。

三、實作方式一:覆寫 onCreateView

a) 先寫布局檔,做一個輸入名稱的簡單表單:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/id_label_your_name"
        android:layout_width="wrap_content"
        android:layout_height="32dp"
        android:gravity="center_vertical"
        android:text="Your name:" />

    <EditText
        android:id="@+id/id_txt_your_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/id_label_your_name"
        android:inputType="text"
        android:imeOptions="actionDone" />

    <Button
        android:id="@+id/id_sure_edit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/id_txt_your_name"
        android:layout_alignParentRight="true"
        android:text="ok" />
</RelativeLayout>

b) 繼承 DialogFragment 並覆寫 onCreateView:

package com.example.zhy_dialogfragment;

import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class EditNameDialogFragment extends DialogFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_edit_name, container);
        return view;
    }
}

c) 在 Activity 中呼叫:

public void showEditDialog(View view) {
    EditNameDialogFragment editNameDialog = new EditNameDialogFragment();
    editNameDialog.show(getFragmentManager(), "EditNameDialog");
}

對話框確實出來了,但頂端多了一條很礙眼的預設標題列。想拿掉,只要在 onCreateView 裡多一行:

public class EditNameDialogFragment extends DialogFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.fragment_edit_name, container);
        return view;
    }
}

標題列乾乾淨淨地被移除了。

四、實作方式二:覆寫 onCreateDialog

既然官方不建議直接用 Dialog,那我們就用 AlertDialog.Builder 做一個登入框。

a) 布局檔:上方放圖,下方放帳號與密碼輸入框。

<?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"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:background="#FFFFBB33"
        android:contentDescription="@string/app_name"
        android:scaleType="center"
        android:src="@drawable/title" />

    <EditText
        android:id="@+id/id_txt_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="4dp"
        android:hint="input"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/id_txt_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:layout_marginBottom="16dp"
        android:fontFamily="sans-serif"
        android:hint="input"
        android:inputType="textPassword" />
</LinearLayout>

b) 覆寫 onCreateDialog:

package com.example.zhy_dialogfragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

public class LoginDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.fragment_login_dialog, null);

        // 因為 view 要放進 dialog 布局,所以 parent 傳 null
        builder.setView(view)
                .setPositiveButton("Sign in", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                    }
                })
                .setNegativeButton("Cancel", null);
        return builder.create();
    }
}

c) 呼叫:

public void showLoginDialog(View view) {
    LoginDialogFragment dialog = new LoginDialogFragment();
    dialog.show(getFragmentManager(), "loginDialog");
}

效果相當不錯,而且正反負按鈕都由 framework 幫你排好了。

五、把資料回傳給 Activity

對話框裡輸入的內容要怎麼送回 Activity?官方推薦的做法是「fragment interface pattern」:在 Fragment 中定義一個介面,要求宿主 Activity 實作它,按下按鈕時透過這個介面把資料交回去。

public class LoginDialogFragment extends DialogFragment {

    private EditText mUsername;
    private EditText mPassword;

    public interface LoginInputListener {
        void onLoginInputComplete(String username, String password);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.fragment_login_dialog, null);

        mUsername = (EditText) view.findViewById(R.id.id_txt_username);
        mPassword = (EditText) view.findViewById(R.id.id_txt_password);

        builder.setView(view)
                .setPositiveButton("Sign in", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        LoginInputListener listener = (LoginInputListener) getActivity();
                        listener.onLoginInputComplete(
                                mUsername.getText().toString(),
                                mPassword.getText().toString());
                    }
                })
                .setNegativeButton("Cancel", null);
        return builder.create();
    }
}

寫法很直白:先拿到兩個輸入框的參照,按下登入時把 Activity 轉型成自訂介面,再呼叫介面方法把帳號密碼送出去。

Activity 端只要實作這個介面即可:

public class MainActivity extends Activity implements LoginInputListener {

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

    public void showLoginDialog(View view) {
        LoginDialogFragment dialog = new LoginDialogFragment();
        dialog.show(getFragmentManager(), "loginDialog");
    }

    @Override
    public void onLoginInputComplete(String username, String password) {
        Toast.makeText(this, "帳號:" + username + ",密碼:" + password,
                Toast.LENGTH_SHORT).show();
    }
}

為什麼不直接用 getArguments() 或公開方法?因為 Fragment 不該假設宿主一定是哪個 Activity,用介面解耦之後,同一顆 Fragment 可以給任何 Activity 複用,也不容易在轉屏重建時出問題。

六、用 DialogFragment 做跨尺寸適配

目標:同一顆 Fragment,在大螢幕上以對話框形式浮現,在小螢幕上直接嵌進 Activity 版面。這個效果只能透過覆寫 onCreateView 達成,所以我們沿用前面的 EditNameDialogFragment。

public void showDialogInDifferentScreen(View view) {
    FragmentManager fragmentManager = getFragmentManager();
    EditNameDialogFragment newFragment = new EditNameDialogFragment();
    boolean mIsLargeLayout = getResources().getBoolean(R.bool.large_layout);

    if (mIsLargeLayout) {
        // 大螢幕:以對話框呈現
        newFragment.show(fragmentManager, "dialog");
    } else {
        // 小螢幕:直接填滿 Activity
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.replace(R.id.id_ly, newFragment).commit();
    }
}

判斷依據是 R.bool.large_layout 這個自訂資源。預設的 values/bools.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="large_layout">false</bool>
</resources>

再新增 res/values-large/bools.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="large_layout">true</bool>
</resources>

系統會依螢幕尺寸自動挑選對應的 values 目錄,一行程式碼都不用改。

左邊是模擬器(大螢幕,走對話框分支),右邊是真機(小螢幕,走嵌入分支)。

七、轉屏時到底差在哪

情境:使用者正在輸入帳號密碼,這時候轉了一下螢幕。如果用傳統寫法,輸入的內容全丟了;更糟的是,Activity 銷毀前若對話框還沒關閉,logcat 會直接丟出 IllegalArgumentException。

我們把前面那個用 AlertDialog 建立的登入框改寫成不經 Fragment 的版本,放在 Activity 裡直接呼叫:

public void showLoginDialogWithoutFragment(View view) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();

    builder.setView(inflater.inflate(R.layout.fragment_login_dialog, null))
            .setPositiveButton("Sign in", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    // sign in the user ...
                }
            })
            .setNegativeButton("Cancel", null)
            .show();
}

實測結果:傳統 Dialog 在旋轉螢幕的瞬間就消失了,後台還伴隨著例外堆疊;改用 DialogFragment 的版本則完全不受影響,連輸入中的文字都還在。這就是官方要你改用 DialogFragment 最實際的理由。

關於 DialogFragment 的介紹就到這裡,有問題歡迎留言討論。

參考文件:

https://developer.android.com/guide/topics/ui/dialogs.html#DialogFragment

https://github.com/thecodepath/android_guides/wiki/Using-DialogFragment

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