Android 官方推薦 : DialogFragment 建立對話方塊
轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/37815413
1、 概述
DialogFragment在android 3.0時被引入。是一種特殊的Fragment,用於在Activity的內容之上展示一個模態的對話方塊。典型的用於:展示警告框,輸入框,確認框等等。在DialogFragment產生之前,我們建立對話方塊:一般採用AlertDialog和Dialog。注:官方不推薦直接使用Dialog建立對話方塊。
2、 好處與用法
使用DialogFragment來管理對話方塊,當旋轉螢幕和按下後退鍵時可以更好的管理其宣告週期,它和Fragment有著基本一致的宣告週期。且DialogFragment也允許開發者把Dialog作為內嵌的元件進行重用,類似Fragment(可以在大螢幕和小螢幕顯示出不同的效果)。上面會通過例子展示這些好處~使用DialogFragment至少需要實現onCreateView或者onCreateDIalog方法。onCreateView即使用定義的xml佈局檔案展示Dialog。onCreateDialog即利用AlertDialog或者Dialog建立出Dialog。
3、 重寫onCreateView建立Dialog
a)佈局檔案,我們建立一個設定名稱的佈局檔案:
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://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>
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)測試執行:
Main方法中呼叫:
- public void showEditDialog(View view)
- {
- EditNameDialogFragment editNameDialog = new EditNameDialogFragment();
- editNameDialog.show(getFragmentManager(), "EditNameDialog");
- }
- 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;
- }
- }
效果圖:
4、 重寫onCreateDialog建立Dialog
在onCreateDialog中一般可以使用AlertDialog或者Dialog建立對話方塊,不過既然google不推薦直接使用Dialog,我們就使用AlertDialog來建立一個登入的對話方塊。
a)佈局檔案
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://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_marginBottom="4dp"
- android:layout_marginLeft="4dp"
- android:layout_marginRight="4dp"
- android:layout_marginTop="16dp"
- android:hint="input username"
- 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>
b)繼承DialogFragment重寫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;
- import android.view.ViewGroup;
- import android.widget.EditText;
- public class LoginDialogFragment extends DialogFragment
- {
- @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)
- // Add action buttons
- .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");
- }
效果圖:
可以看到通過重寫onCreateDialog同樣可以實現建立對話方塊,效果還是很nice的。
5、傳遞資料給Activity
從dialog傳遞資料給Activity,可以使用“fragment interface pattern”的方式,下面通過一個改造上面的登入框來展示這種模式。
改動比較小,直接貼程式碼了:
- 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;
- import android.view.ViewGroup;
- import android.widget.EditText;
- 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());
- // Get the layout inflater
- 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);
- // Inflate and set the layout for the dialog
- // Pass null as the parent view because its going in the dialog layout
- builder.setView(view)
- // Add action buttons
- .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();
- }
- }
拿到username和password的引用,在點選登入的時候,把activity強轉為我們自定義的介面:LoginInputListener,然後將使用者輸入的資料返回。
MainActivity中需要實現我們的介面LoginInputListener,實現我們的方法,就可以實現當使用者點選登陸時,獲得我們的帳號密碼了:
- c) MainActivity
- package com.example.zhy_dialogfragment;
- import com.example.zhy_dialogfragment.LoginDialogFragment.LoginInputListener;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.content.DialogInterface;
- import android.os.Bundle;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.widget.Toast;
- 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();
- }
- }
效果:
6、DialogFragment做螢幕適配
我們希望,一個對話方塊在大螢幕上以對話方塊的形式展示,而小螢幕上則直接嵌入當前的Actvity中。這種效果的對話方塊,只能通過重寫onCreateView實現。下面我們利用上面的EditNameDialogFragment來顯示。
EditNameDialogFragment我們已經編寫好了,直接在MainActivity中寫呼叫
- 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();
- }
- }
可以看到,我們通過讀取R.bool.large_layout,然後根據得到的布林值,如果是大螢幕則直接以對話方塊顯示,如果是小螢幕則嵌入我們的Activity佈局中
這個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,在values-large下再新建一個bools.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <bool name="large_layout">true</bool>
- </resources>
最後測試:
左邊為模擬器,右邊為我的手機~~~~~
7、螢幕旋轉
當使用者輸入帳號密碼時,忽然旋轉了一下螢幕,帳號密碼不見了~~~是不是會抓狂
傳統的new AlertDialog在螢幕旋轉時,第一不會儲存使用者輸入的值,第二還會報異常,因為Activity銷燬前不允許對話方塊未關閉。而通過DialogFragment實現的對話方塊則可以完全不必考慮旋轉的問題。
我們直接把上面登入使用AlertDialog建立的登入框,拷貝到MainActivity中直接呼叫:
- public void showLoginDialogWithoutFragment(View view)
- {
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- // Get the layout inflater
- LayoutInflater inflater = this.getLayoutInflater();
- // Inflate and set the layout for the dialog
- // Pass null as the parent view because its going in the dialog layout
- builder.setView(inflater.inflate(R.layout.fragment_login_dialog, null))
- // Add action buttons
- .setPositiveButton("Sign in",
- new DialogInterface.OnClickListener()
- {
- @Override
- public void onClick(DialogInterface dialog, int id)
- {
- // sign in the user ...
- }
- }).setNegativeButton("Cancel", null).show();
- }
下面我分別點選兩種方式建立的登入框,看效果圖:
可以看到,傳統的Dialog旋轉螢幕時就消失了,且後臺log會報異常~~~使用DialogFragment則不受影響。
好了,關於DialogFragment的介紹結束~~~~
有任何疑問請留言
參考文件:
http://developer.android.com/guide/topics/ui/dialogs.html#DialogFragment
https://github.com/thecodepath/android_guides/wiki/Using-DialogFragment
相關文章
- android 多項對話方塊Android
- Android Dialog對話方塊Android
- android常用對話方塊封裝Android封裝
- Android對話方塊Dialog深度剖析Android
- Android 對話方塊 Dialog 深度剖析Android
- Android通知之普通對話方塊通知Android
- Android通知之列表對話方塊通知Android
- Android通知之多選對話方塊通知Android
- 編輯Android程式遊戲對話方塊Android遊戲
- Android UI系列-----Dialog對話方塊AndroidUI
- 建立互動式shell指令碼對話方塊指令碼
- Android通知之單選對話方塊通知Android
- 對話方塊函式函式
- c#中的模態對話方塊和非模態對話方塊C#
- [MFC]選擇目錄對話方塊和選擇檔案對話方塊
- Android通知之進度條對話方塊通知Android
- Android自定義View(1):對話方塊-DialogAndroidView
- JavaScript視窗功能指南之建立對話方塊 (轉)JavaScript
- flutter demo (四):對話方塊Flutter
- Javascript檔案對話方塊JavaScript
- Android UI控制元件系列:Dialog(對話方塊)AndroidUI控制元件
- React中的模式對話方塊React模式
- 在 Flutter 使用 GetX 對話方塊Flutter
- Qt 對話方塊新增工具欄QT
- 如何自學qt(4)——對話方塊QT
- QT 等待對話方塊/進度QT
- 視窗和對話方塊居中對齊
- 建造者模式打造隨心所欲的Android對話方塊模式Android
- Android——最全的系統對話方塊(AlertDialog)詳解Android
- Android AlterDialog 常用對話方塊使用方法詳解Android
- 模態對話方塊與非模態對話的幾種銷燬方法與區別薦
- Flutter Widgets 對話方塊-DialogFlutter
- 常用元件 / 對話方塊及選單元件
- Qt標準對話方塊實現QT
- TWebBrowser禁止彈出Alert對話方塊Web
- 一個Flex 對話方塊的坑Flex
- javascript中的彈出對話方塊JavaScript
- JavaScript彈出儲存對話方塊JavaScript