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

DialogFragment 完整指南:Android 官方推薦的對話框實現方式

編輯:關於 Android 程式設計

一、概述

DialogFragment 從 Android 3.0 開始引入,它是一種特殊的 Fragment,用於在 Activity 內容之上顯示一個模態對話框,典型場景是警告框、輸入框、確認框等。

在它出現之前,我們通常用 AlertDialog 或 Dialog 直接建對話框。要注意的是,官方並不推薦直接使用 Dialog。

二、好處與用法

用 DialogFragment 來管理對話框,在旋轉螢幕與按下返回鍵時能更好地掌控其生命週期——它的生命週期與 Fragment 基本一致。此外,DialogFragment 也允許你把 Dialog 當成內嵌組件重複利用,在大螢幕與小螢幕上呈現不同形態。

使用 DialogFragment 至少要實作 onCreateView 或 onCreateDialog 其中之一:前者用自訂的 XML 布局呈現 Dialog,後者則用 AlertDialog 或 Dialog 來構建。

三、覆寫 onCreateView 建立 Dialog

先準備一個輸入名稱的布局:

<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:imeOptions="actionDone"
        android:inputType="text" />

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

接著繼承 DialogFragment,覆寫 onCreateView:

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;
    }
}

在 Activity 中呼叫:

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

對話框成功顯示了,但預設帶一個很礙眼的標題列。想去掉?在 onCreateView 中呼叫 getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE); 即可:

@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

onCreateDialog 中通常用 AlertDialog 或 Dialog。既然官方不推薦直接用 Dialog,我們就用 AlertDialog 做一個登入框。

布局如下:

<LinearLayout
    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_marginBottom="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="16dp"
        android:hint="input user name"
        android:inputType="textEmailAddress" />

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

覆寫 onCreateDialog:

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();
    }
}

呼叫方式與前面相同:

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

效果很不錯。

五、把資料回傳給 Activity

要從 Dialog 把資料傳回 Activity,官方的建議做法是「fragment interface pattern」。我們改寫一下上面的登入框:

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();
    }
}

六、用 DialogFragment 做螢幕適配

我們常有一個需求:同一個對話框在大螢幕上以彈窗形式出現,在小螢幕上則直接嵌入 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) {
        // 大螢幕:以 dialog 形式顯示
        newFragment.show(fragmentManager, "dialog");
    } else {
        // 小螢幕:直接填滿螢幕
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.replace(R.id.id_ly, newFragment).commit();
    }
}

關鍵在於讀取 R.bool.large_layout 這個自訂資源。預設的 res/values/bools.xml:

<resources>
    <bool name="large_layout">false</bool>
</resources>

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

<resources>
    <bool name="large_layout">true</bool>
</resources>

測試結果(左為模擬器,右為實機):

七、螢幕旋轉

使用者正在輸入帳號密碼,突然轉了一下螢幕,內容全沒了——這一定會讓人抓狂。

傳統 new AlertDialog 的做法有兩個問題:一是旋轉時不會保留使用者已輸入的值,二是會拋異常,因為 Activity 銷毀前不允許還有未關閉的對話框。而 DialogFragment 完全不必操心這些。

對比一下傳統寫法:

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 的介紹就到這裡,有疑問歡迎留言討論。

參考資料:
Android 官方開發者指南 Dialogs 章節
thecodepath/android_guides 的 Using-DialogFragment

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