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

DialogFragment 全面解析:從原理到進階用法

編輯:關於 Android 開發

DialogFragment 全面解析:從原理到進階用法

原博客地址:https://www.cnblogs.com/tianzhijiexian/p/4161811.html

相信看到這篇文章的朋友,對 Android 中的 Dialog 都不陌生。隨著 Fragment 這個類的引入,Google 官方推薦大家使用 DialogFragment 來代替傳統的 Dialog。那麼,之前學過的 Dialog 知識是不是就沒用了呢?非也。新的 DialogFragment 是為了讓大家更好地管理和重用 Dialog,之前的知識其實都能拿來即用,僅需少許改動。

一、Dialog 和 DialogFragment 的區別與優劣

新來的 DialogFragment 讓 Dialog 也變成了「碎片」,對程式員而言,對話框現在更具體了——它就是一個 Activity 上的一個 Fragment,我們可以用 Fragment 的知識來管理對話框。

先看看之前是怎麼使用對話框對象的:

 AlertDialog dialog = new AlertDialog.Builder(this) .setTitle("Dialog") .setMessage("thisis a dialog") .show();

如果這時螢幕方向發生變化,就會導致 Activity 重建,之前顯示的對話框便不見了,查看 log 還會發現這樣的錯誤:

04-1917:30:06.999: E/WindowManager(14495): Activitycom.example.androidtest.MainActivity has leaked windowcom.android.internal.policy.impl.PhoneWindow$DecorView{42ca3c18 V.E.....R....... 0,0-1026,414} that was originally added here

我們也可以無視這個錯誤,因為程式不會因此崩潰(看來 Android 本身就預料到這種情況了)。若想讓螢幕旋轉時對話框依然顯示,就得做額外處理:在 Activity 銷毀前設立一個標志,記錄對話框是否處於顯示狀態,下次建立時再直接顯示。

在 onSaveInstanceState 中:

@Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (dialog != null && dialog.isShowing()) { outState.putBoolean("DIALOG_SHOWN", true); } }

在 onCreate 中:

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { boolean isShown = savedInstanceState.getBoolean("DIALOG_SHOWN"); if (isShown) { AlertDialog dialog = new AlertDialog.Builder(this).setTitle("Dialog") .setMessage("thisis a dialog").show(); } } …… }

而用 DialogFragment 來管理對話框就不會有這種問題了,程式碼也少了許多邏輯處理。當你旋轉螢幕時,FragmentManager 會自動管理 DialogFragment 的生命週期,若當前已顯示在螢幕上,旋轉後也會自動顯示。下面是螢幕旋轉時的 log 輸出:

04-1917:45:41.289: D/==========(16156): MyDialogFragment : onAttach

04-1917:45:41.299: D/==========(16156): MyDialogFragment : onCreate

04-1917:45:41.299: D/==========(16156): MyDialogFragment : onCreateView

04-1917:45:41.309: D/==========(16156): MyDialogFragment : onStart

04-1917:45:50.619: D/==========(16156): MyDialogFragment : onStop

04-1917:45:50.619: D/==========(16156): third activity on destroy

04-1917:45:50.619:D/==========(16156): MyDialogFragment : onDestroyView

04-1917:45:50.619: D/==========(16156): MyDialogFragment : onDetach

04-1917:45:50.639: D/==========(16156): MyDialogFragment : onAttach

04-1917:45:50.639: D/==========(16156): MyDialogFragment : onCreate

04-1917:45:50.659: D/==========(16156): MyDialogFragment : onCreateView

04-1917:45:50.659: D/==========(16156): MyDialogFragment : onStart

你也可能不以為然,說自己的應用就是豎屏用的,開著對話框旋轉來旋轉去畢竟是極少數。那麼下面的好處你一定無法否定:以前用 Dialog 時,必須在 Activity 中建立這個對象並掛上監聽器,程式碼冗長且破壞 Activity 的邏輯性。而對話框這種自成一體、又需要重用的東西,為什麼不乾脆用 DialogFragment 來實現呢?它不僅能更方便地管理對話框,還能在旋轉螢幕和按返回鍵時更好地管理生命週期,甚至允許把 Dialog 作為內嵌元件重用——在大螢幕上直接內嵌顯示,在小螢幕上才彈出對話框,非常靈活。

二、DialogFragment 的最簡單用法

使用 DialogFragment 甚至比用 Fragment 還簡單,因為 API 已經幫你實現了 fragment 切換對象。

1. 建立一個 fragment 對象

package com.kale.dialogfragmenttest; import android.app.DialogFragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class MyDialogFragment extends DialogFragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { System.out.println("tag = "+getTag()); // tag which is from acitivity which started this fragment return inflater.inflate(R.layout.dialog, null); } }

我們建立一個繼承自 DialogFragment 的 fragment,在 onCreateView 中透過布局檔建立一個 view,這和 fragment 完全一致。布局檔如下:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" /> <EditText android:layout_marginTop="10dp" android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10"> <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_marginTop="10dp" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout>

2. 在 Activity 中啟用這個 dialog

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new DialogFragmentTest() .show(getFragmentManager(), "dialog_fragment"); }

很像 Dialog 吧,同樣支援鏈式編程。這裡的參數:① 一個 FragmentManager(低版本用 getSupport 獲取);② 一個 tag(String),透過它能告訴 fragment 是誰啟動了它,在 fragment 中可用 getTag() 獲取。

多說一句:如今低版本用戶已經很少,甚至可以不再費心相容 2.x 系統了。很多曾經至關重要的技術,在新的發展中已慢慢變得無足輕重,但我們為之付出的經歷,卻是寶貴的閱歷與談資。

下面是運行效果:

有人說上面那個空白的 title 很醜,想去掉。當然可以,這正是 fragment 的靈活之處:

getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

public class MyDialogFragment extends DialogFragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { System.out.println("tag = "+getTag());  getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE); return inflater.inflate(R.layout.dialog, null); } }

現在它變成了這樣:

可以看到,任何改變都是有代價的:若你仍用 match_parent 指定控件寬度,就會變成這種自適應的窄寬度。那個 title 欄就像支撐對話框寬度的「房梁」,沒了它寬度就只能自適應,解法就是手動指定控件寬度。

注意:如果你的 DialogFragment 是 Activity 的內部類,必須將它定義為 static 的,否則會報錯!

 public static class DialogFragmentTest extends DialogFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO 自動生成的方法存根 return inflater.inflate(R.layout.dialog, null); } }

三、DialogFragment 啟動、終止過程分析

我們使用前沒有像 fragment 那樣建立加載對象、也沒有 commit,卻能用 DialogFragment,這是為什麼呢?先來看它的源碼。

1. show()

 public void show(FragmentManager manager, String tag){ mDismissed = false; mShownByMe = true; FragmentTransaction ft = manager.beginTransaction(); // creat a fragmentTransaction ft.add(this, tag); // add fragment with tag ft.commit(); }

真相大白:API 自動幫你實現了一個 fragment 切換對象,並在 show 時就已經 add 了 fragment。add 中沒有提供容器 id,表示加載到當前 Activity 中,添加後也確實調用了 commit。

2. show() 的另一種形式

 public int show(FragmentTransaction transaction, String tag) { mDismissed = false; mShownByMe = true; transaction.add(this, tag); mViewDestroyed = false; mBackStackId = transaction.commit(); return mBackStackId; } 

這種形式傳入的是一個 FragmentTransaction 對象,我們可以傳入一個已配置好的 transaction,大大增加了可定制性。

3. dismiss()

** * Dismiss the fragment and its dialog. If the fragment was added to the * back stack, all back stack state up to and including this entry will * be popped. Otherwise, a new transaction will be committed to remove * the fragment. */ public void dismiss() { dismissInternal(false); } void dismissInternal(boolean allowStateLoss) { if (mDismissed) { return; } mDismissed = true; mShownByMe = false; if (mDialog != null) { mDialog.dismiss(); mDialog = null; } mViewDestroyed = true; if (mBackStackId >= 0) { getFragmentManager().popBackStack(mBackStackId, FragmentManager.POP_BACK_STACK_INCLUSIVE); mBackStackId = -1; } else { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.remove(this); if (allowStateLoss) { ft.commitAllowingStateLoss(); } else { ft.commit(); } } } 

由此可見,關閉 DialogFragment 時會先檢查堆棧:若 back stack 有該 Dialog 就將其 pop 出來,否則直接 ft.remove(this) 再 ft.commit()。調用 dismiss() 會觸發 onDismiss() 回呼。

四、透過 onCreateView() 建立對話框布局

上面的例子已在 onCreateView() 建立了自定義布局,這時 fragment 建立布局的傳統寫法,很適合用於自定義對話框。我們可以在 onCreate 中設置對話框的風格與屬性,但千萬別設置關於 view 的東西(此時對話框還沒建立),有關 view 的設置留到 onCreateView 中。下面簡單設置一個 button 點擊事件——關閉對話框:

public class MyDialogFragment extends DialogFragment{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //如果setCancelable()中參數為true,若點擊dialog覆蓋不到的activity的空白或者按返回鍵, //則進行cancel,狀態檢測依次onCancel()和onDismiss()。如參數為false,則按空白處或返回鍵無反應。缺省為true setCancelable(true); //可以設置dialog的顯示風格 //setStyle(style,theme); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE); View rootView = inflater.inflate(R.layout.dialog, null); Button btn = (Button)rootView.findViewById(R.id.button); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO 自動生成的方法存根 dismiss(); } }); return rootView; } }

補充:實現信息保存。在 Activity 橫豎屏切換時,DialogFragment 現在可以自動重建。若你在 editText 中輸入了信息,4.2 和 4.4 中對話框會人性化地自動保存,無須手動處理;但若測試機被奇葩地定制過,就乖乖手動保存吧:

public class MyDialogFragment extends DialogFragment { EditText editText; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.dialog, null); editText = (EditText) rootView.findViewById(R.id.editText); if (savedInstanceState != null) { CharSequence text = savedInstanceState.getCharSequence("input data"); editText.setText(text == null ? "" : text); } return rootView; } @Override public void onSaveInstanceState(Bundle outState) { outState.putCharSequence("input data", editText.getText()); super.onSaveInstanceState(outState); } }

五、透過 onCreateDialog() 快捷建立對話框

如果沒有自定義布局的需求,怎麼辦?快用 onCreateDialog 吧!這個回呼方法是 DialogFragment 獨有的,它返回一個 Dialog 對象並顯示到螢幕上。千萬別同時使用 onCreateView 和 onCreateDialog,它們只是完成同一目的的兩條路。從生命週期順序而言,先執行 onCreateDialog(),後執行 onCreateView()。

下面在 onCreateDialog 建立一個警告對話框的 builder,透過 create() 生成 AlertDialog 對象返回:

public class MyDialogFragment extends DialogFragment implements android.content.DialogInterface.OnClickListener{ @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("用戶申明") .setMessage(getResources().getString(R.string.hello_world)) .setPositiveButton("我同意", this) .setNegativeButton("不同意", this) .setCancelable(false); //.show(); // show cann't be use here return builder.create(); } @Override public void onClick(DialogInterface dialog, int which) { // TODO 自動生成的方法存根 } }

顯示效果:

看到了嗎?這裡的標題欄終於派上用場了。

注意:① 這裡創建的是一個 dialog,所以用的 onClickListener 自然是对話框中的 listener;② 千萬別在構建對話框對象時順手寫了 show(),我們現在只是在 fragment 中初始化,真正顯示是在 Activity 中進行的,若寫了 show 會出現兩個對話框!

同樣,你也可以在這裡自定義 view,Dialog.builder 本身就提供了 setView 方法:

 @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.fragment_login_dialog, null); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(view) // set your own view // Add action buttons .setPositiveButton("Sign in", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }).setNegativeButton("Cancel", null); return builder.create(); } 

自定義視圖對話框的代碼片段:

/** * 自定義視圖對話框 * * @param title */ public void viewDialog(String title) { // LayoutInflater是用來找layout文件夾下的xml布局文件,並且實例化 LayoutInflater factory = LayoutInflater.from(mContext); // 把activity_login中的控件定義在View中 View view = factory.inflate(R.layout.dialog_layout, null); // 將LoginActivity中的控件顯示在對話框中 // 獲取用戶輸入的“用戶名”,“密碼” // 注意:view.findViewById很重要,因為上面factory.inflate(R.layout.activity_login, // null)將頁面布局賦值給了view了 TextView titleTv = (TextView) view .findViewById(R.id.dialog_textView_id); titleTv.setText(title); Button btn = (Button) view.findViewById(R.id.dialog_logout_button_id); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { showToast("按下自定義視圖的按鈕了~"); } }); builder // 設定顯示的View .setView(view); // 設置dialog是否為模態,false表示模態,true表示非模態 // ab.setCancelable(false); // 對話框的創建、顯示,這裡顯示的位置是在屏幕的最下面,但是很不推薦這個種做法,因為距底部有一段空隙 AlertDialog dialog = builder.create(); Window window = dialog.getWindow(); window.setGravity(Gravity.BOTTOM); // 此處可以設置dialog顯示的位置 window.setWindowAnimations(R.style.myAnimationstyle); // 添加動畫 dialog.show(); }

六、DialogFragment 與 Activity 之間通信

思路很簡單:定義一個傳輸數據的接口,強制 Activity 實現它,在 fragment 需要傳遞數據時調用這個接口的方法即可。好的編程風格是把 fragment 涉及的方法以接口方式封裝起來。

1. 寫一個接口 DataCallback

package com.kale.dialogfragmenttest; public interface DataCallback { public void getData(String data); }

2. Activity 實現這個接口

public class MainActivity extends Activity implements DataCallback{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new MyDialogFragment() .show(getFragmentManager(), "dialog_fragment"); } @Override public void getData(String data) { // TODO 自動生成的方法存根 System.out.println("data = "+ data); } }

3. 在 DialogFragment 中使用這個接口,並用 instanceof 檢查啟動它的 Activity 是否實現了接口,若沒實現就拋出異常,這樣能保證大型項目中不會忘記實現接口:

import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; public class MyDialogFragment extends DialogFragment implements android.content.DialogInterface.OnClickListener { @Override public void onAttach(Activity activity) { // onAttach()是合適的早期階段進行檢查MyActivity是否真的實現了接口。 // 采用接口的方式,dialog無需詳細了解MyActivity,只需了解其所需的接口函數,這是真正項目中應采用的方式。 if (!(activity instanceof DataCallback)) { throw new IllegalStateException("fragment所在的Activity必須實現Callbacks接口"); } super.onAttach(activity); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("用戶申明") .setMessage(getResources().getString(R.string.hello_world)) .setPositiveButton("我同意", this).setNegativeButton("不同意", this) .setCancelable(false); // show(); return builder.create(); } @Override public void onClick(DialogInterface dialog, int which) { // TODO 自動生成的方法存根 DataCallback callback = (DataCallback) getActivity(); callback.getData("test"); } }

此外,fragment 也可以透過 FragmentManager 與 tag 獲取其他 fragment 實例進行通信,但從編程思想看,fragment 之間過多交叉調用不利於程式管控。

七、用 DialogFragment 實現再次彈窗

有時我們需要點擊對話框中的按鈕後再彈出一個對話框。做法是:先在點擊事件中把當前對話框從螢幕移除並壓棧,再建立一個新的 dialogFragment show 出來。雖然讓它從螢幕消失,但仍可透過 FragmentManager 在回退棧中找到它。

 FragmentTransaction ft = getFragmentManager().beginTransaction(); /* * 如果不執行remove(),對話框即不會進入onDismiss()狀態。會被顯示在新的對話框下方,是可見的。 * 主要考慮美觀的問題,如果下面的對話框大於上面的對話框就很難看了。 對於Dialog,container為0或者null。 */ ft.remove(this); /* * 將當前的PromptDialogFragment加入到回退堆棧,當用戶按返回鍵,或者通過按幫助框的Close按鈕dismiss幫助框是, * 重新顯示提示框。 對於back stack的處理,系統具有一定的智能。例如:執行兩次addToStackStack(),實際不會重復壓棧。 * 有例如:注釋掉remove()語句,即提示框不消失,而是在幫助框的下面。 * 但是在實驗中發現是否有addToBackStack()都不會結果有影響,系統能夠分析到對象存在,不需要壓棧。沒有去查源代碼, * 猜測通過mBackStackId比對來進行智能處理。 */ ft.addToBackStack(null); new OhterDialogFragment() .show(getFragmentManager(), "dialog_fragment");

八、利用 Fragment 特性為不同螢幕做適配

如果想在大螢幕顯示對話框、小螢幕則直接把內容放進 Activity 顯示呢?其實很簡單,因為 DialogFragment 本身就是 fragment,既能用 show() 當 dialog 顯示,也能用 FragmentTransaction 放進任意布局。剩下的就是判斷螢幕大小。

在默認的 values 下新建 bools.xml:

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

再在 res 下新建 values-large,並在其中新建 bools.xml,透過加載不同的 value 就能判斷是大螢幕還是小螢幕:

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

在程式碼中進行判斷:

public void showDialogInDifferentScreen(View view) { FragmentManager fragmentManager = getFragmentManager(); EditNameDialogFragment newFragment = new EditNameDialogFragment(); boolean mIsLargeLayout = getResources().getBoolean(R.bool.large_layout) ; Log.e("TAG", mIsLargeLayout+""); if (mIsLargeLayout ) { // The device is using a large layout, so show the fragment as a // dialog newFragment.show(fragmentManager, "dialog"); } else { // The device is smaller, so show the fragment fullscreen FragmentTransaction transaction = fragmentManager.beginTransaction(); // For a little polish, specify a transition animation transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); // To make it fullscreen, use the 'content' root view as the // container for the fragment, which is always the root view for the activity transaction.replace(R.id.id_ly, newFragment).commit(); } } 

參考自:

https://blog.csdn.net/huangyabin001/article/details/30053835

https://blog.csdn.net/lmj623565791/article/details/37815413

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