转载请标明出处: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)布局文件,我们创建一个设置名称的布局文件:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="wrap_content"
  4. android:layout_height="wrap_content" >
  5. <TextView
  6. android:id="@+id/id_label_your_name"
  7. android:layout_width="wrap_content"
  8. android:layout_height="32dp"
  9. android:gravity="center_vertical"
  10. android:text="Your name:" />
  11. <EditText
  12. android:id="@+id/id_txt_your_name"
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. android:layout_toRightOf="@id/id_label_your_name"
  16. android:imeOptions="actionDone"
  17. android:inputType="text" />
  18. <Button
  19. android:id="@+id/id_sure_edit_name"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:layout_alignParentRight="true"
  23. android:layout_below="@id/id_txt_your_name"
  24. android:text="ok" />
  25. </RelativeLayout>

b)继承DialogFragment,重写onCreateView方法

  1. package com.example.zhy_dialogfragment;
  2. import android.app.DialogFragment;
  3. import android.os.Bundle;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. public class EditNameDialogFragment extends DialogFragment
  8. {
  9. @Override
  10. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  11. Bundle savedInstanceState)
  12. {
  13. View view = inflater.inflate(R.layout.fragment_edit_name, container);
  14. return view;
  15. }
  16. }

c)测试运行:

Main方法中调用:

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

效果图:

可以看到,对话框成功创建并显示出来,不过默认对话框有个讨厌的标题,我们怎么去掉呢:可以在onCreateView中调用getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);即可去掉。即:
  1. public class EditNameDialogFragment extends DialogFragment
  2. {
  3. @Override
  4. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  5. Bundle savedInstanceState)
  6. {
  7. getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
  8. View view = inflater.inflate(R.layout.fragment_edit_name, container);
  9. return view;
  10. }
  11. }

效果图:

很完美的去掉了讨厌的标题。
 
4、 重写onCreateDialog创建Dialog

在onCreateDialog中一般可以使用AlertDialog或者Dialog创建对话框,不过既然google不推荐直接使用Dialog,我们就使用AlertDialog来创建一个登录的对话框。

a)布局文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="wrap_content"
  4. android:layout_height="wrap_content"
  5. android:orientation="vertical" >
  6. <ImageView
  7. android:layout_width="match_parent"
  8. android:layout_height="64dp"
  9. android:background="#FFFFBB33"
  10. android:contentDescription="@string/app_name"
  11. android:scaleType="center"
  12. android:src="@drawable/title" />
  13. <EditText
  14. android:id="@+id/id_txt_username"
  15. android:layout_width="match_parent"
  16. android:layout_height="wrap_content"
  17. android:layout_marginBottom="4dp"
  18. android:layout_marginLeft="4dp"
  19. android:layout_marginRight="4dp"
  20. android:layout_marginTop="16dp"
  21. android:hint="input username"
  22. android:inputType="textEmailAddress" />
  23. <EditText
  24. android:id="@+id/id_txt_password"
  25. android:layout_width="match_parent"
  26. android:layout_height="wrap_content"
  27. android:layout_marginBottom="16dp"
  28. android:layout_marginLeft="4dp"
  29. android:layout_marginRight="4dp"
  30. android:layout_marginTop="4dp"
  31. android:fontFamily="sans-serif"
  32. android:hint="input password"
  33. android:inputType="textPassword" />
  34. </LinearLayout>

b)继承DialogFragment重写onCreateDialog方法

  1. package com.example.zhy_dialogfragment;
  2. import android.app.AlertDialog;
  3. import android.app.Dialog;
  4. import android.app.DialogFragment;
  5. import android.content.DialogInterface;
  6. import android.os.Bundle;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;
  10. import android.widget.EditText;
  11. public class LoginDialogFragment extends DialogFragment
  12. {
  13. @Override
  14. public Dialog onCreateDialog(Bundle savedInstanceState)
  15. {
  16. AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  17. // Get the layout inflater
  18. LayoutInflater inflater = getActivity().getLayoutInflater();
  19. View view = inflater.inflate(R.layout.fragment_login_dialog, null);
  20. // Inflate and set the layout for the dialog
  21. // Pass null as the parent view because its going in the dialog layout
  22. builder.setView(view)
  23. // Add action buttons
  24. .setPositiveButton("Sign in",
  25. new DialogInterface.OnClickListener()
  26. {
  27. @Override
  28. public void onClick(DialogInterface dialog, int id)
  29. {
  30. }
  31. }).setNegativeButton("Cancel", null);
  32. return builder.create();
  33. }
  34. }

c)调用

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

效果图:

可以看到通过重写onCreateDialog同样可以实现创建对话框,效果还是很nice的。

5、传递数据给Activity

从dialog传递数据给Activity,可以使用“fragment interface pattern”的方式,下面通过一个改造上面的登录框来展示这种模式。

改动比较小,直接贴代码了:

  1. package com.example.zhy_dialogfragment;
  2. import android.app.AlertDialog;
  3. import android.app.Dialog;
  4. import android.app.DialogFragment;
  5. import android.content.DialogInterface;
  6. import android.os.Bundle;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;
  10. import android.widget.EditText;
  11. public class LoginDialogFragment extends DialogFragment
  12. {
  13. private EditText mUsername;
  14. private EditText mPassword;
  15. public interface LoginInputListener
  16. {
  17. void onLoginInputComplete(String username, String password);
  18. }
  19. @Override
  20. public Dialog onCreateDialog(Bundle savedInstanceState)
  21. {
  22. AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  23. // Get the layout inflater
  24. LayoutInflater inflater = getActivity().getLayoutInflater();
  25. View view = inflater.inflate(R.layout.fragment_login_dialog, null);
  26. mUsername = (EditText) view.findViewById(R.id.id_txt_username);
  27. mPassword = (EditText) view.findViewById(R.id.id_txt_password);
  28. // Inflate and set the layout for the dialog
  29. // Pass null as the parent view because its going in the dialog layout
  30. builder.setView(view)
  31. // Add action buttons
  32. .setPositiveButton("Sign in",
  33. new DialogInterface.OnClickListener()
  34. {
  35. @Override
  36. public void onClick(DialogInterface dialog, int id)
  37. {
  38. LoginInputListener listener = (LoginInputListener) getActivity();
  39. listener.onLoginInputComplete(mUsername
  40. .getText().toString(), mPassword
  41. .getText().toString());
  42. }
  43. }).setNegativeButton("Cancel", null);
  44. return builder.create();
  45. }
  46. }

拿到username和password的引用,在点击登录的时候,把activity强转为我们自定义的接口:LoginInputListener,然后将用户输入的数据返回。

MainActivity中需要实现我们的接口LoginInputListener,实现我们的方法,就可以实现当用户点击登陆时,获得我们的帐号密码了:

  1. c)  MainActivity
  2. package com.example.zhy_dialogfragment;
  3. import com.example.zhy_dialogfragment.LoginDialogFragment.LoginInputListener;
  4. import android.app.Activity;
  5. import android.app.AlertDialog;
  6. import android.content.DialogInterface;
  7. import android.os.Bundle;
  8. import android.view.LayoutInflater;
  9. import android.view.View;
  10. import android.widget.Toast;
  11. public class MainActivity extends Activity implements LoginInputListener
  12. {
  13. @Override
  14. protected void onCreate(Bundle savedInstanceState)
  15. {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_main);
  18. }
  19. public void showLoginDialog(View view)
  20. {
  21. LoginDialogFragment dialog = new LoginDialogFragment();
  22. dialog.show(getFragmentManager(), "loginDialog");
  23. }
  24. @Override
  25. public void onLoginInputComplete(String username, String password)
  26. {
  27. Toast.makeText(this, "帐号:" + username + ",  密码 :" + password,
  28. Toast.LENGTH_SHORT).show();
  29. }
  30. }

效果:

6、DialogFragment做屏幕适配

我们希望,一个对话框在大屏幕上以对话框的形式展示,而小屏幕上则直接嵌入当前的Actvity中。这种效果的对话框,只能通过重写onCreateView实现。下面我们利用上面的EditNameDialogFragment来显示。

EditNameDialogFragment我们已经编写好了,直接在MainActivity中写调用

  1. public void showDialogInDifferentScreen(View view)
  2. {
  3. FragmentManager fragmentManager = getFragmentManager();
  4. EditNameDialogFragment newFragment = new EditNameDialogFragment();
  5. boolean mIsLargeLayout = getResources().getBoolean(R.bool.large_layout) ;
  6. Log.e("TAG", mIsLargeLayout+"");
  7. if (mIsLargeLayout )
  8. {
  9. // The device is using a large layout, so show the fragment as a
  10. // dialog
  11. newFragment.show(fragmentManager, "dialog");
  12. } else
  13. {
  14. // The device is smaller, so show the fragment fullscreen
  15. FragmentTransaction transaction = fragmentManager
  16. .beginTransaction();
  17. // For a little polish, specify a transition animation
  18. transaction
  19. .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
  20. // To make it fullscreen, use the 'content' root view as the
  21. // container
  22. // for the fragment, which is always the root view for the activity
  23. transaction.replace(R.id.id_ly, newFragment)
  24. .commit();
  25. }
  26. }

可以看到,我们通过读取R.bool.large_layout,然后根据得到的布尔值,如果是大屏幕则直接以对话框显示,如果是小屏幕则嵌入我们的Activity布局中

这个R.bool.large_layout是我们定义的资源文件:

在默认的values下新建一个bools.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <bool name="large_layout">false</bool>
  4. </resources>

然后在res下新建一个values-large,在values-large下再新建一个bools.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <bool name="large_layout">true</bool>
  4. </resources>

最后测试:

          

左边为模拟器,右边为我的手机~~~~~

7、屏幕旋转

当用户输入帐号密码时,忽然旋转了一下屏幕,帐号密码不见了~~~是不是会抓狂

传统的new AlertDialog在屏幕旋转时,第一不会保存用户输入的值,第二还会报异常,因为Activity销毁前不允许对话框未关闭。而通过DialogFragment实现的对话框则可以完全不必考虑旋转的问题。

我们直接把上面登录使用AlertDialog创建的登录框,拷贝到MainActivity中直接调用:

  1. public void showLoginDialogWithoutFragment(View view)
  2. {
  3. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  4. // Get the layout inflater
  5. LayoutInflater inflater = this.getLayoutInflater();
  6. // Inflate and set the layout for the dialog
  7. // Pass null as the parent view because its going in the dialog layout
  8. builder.setView(inflater.inflate(R.layout.fragment_login_dialog, null))
  9. // Add action buttons
  10. .setPositiveButton("Sign in",
  11. new DialogInterface.OnClickListener()
  12. {
  13. @Override
  14. public void onClick(DialogInterface dialog, int id)
  15. {
  16. // sign in the user ...
  17. }
  18. }).setNegativeButton("Cancel", null).show();
  19. }

下面我分别点击两种方式创建的登录框,看效果图:

可以看到,传统的Dialog旋转屏幕时就消失了,且后台log会报异常~~~使用DialogFragment则不受影响。

好了,关于DialogFragment的介绍结束~~~~

有任何疑问请留言

源码点击下载

参考文档:

http://developer.Android.com/guide/topics/ui/dialogs.html#DialogFragment

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

Android 官方推荐 : DialogFragment 创建对话框的更多相关文章

  1. [Android Pro] Android 官方推荐 : DialogFragment 创建对话框

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37815413 1. 概述 DialogFragment在android 3.0时 ...

  2. 转帖:Android 官方推荐 : DialogFragment 创建对话框

    转: Android 官方推荐 : DialogFragment 创建对话框 复制内容,留作备份 1. 概述 DialogFragment在android 3.0时被引入.是一种特殊的Fragment ...

  3. Android控件大全(一)——DialogFragment创建对话框

    DialogFragment在android 3.0时被引入.是一种特殊的Fragment,用于在Activity的内容之上展示一个模态的对话框.典型的用于:展示警告框,输入框,确认框等等. 在Dia ...

  4. Android官方推荐使用DialogFragment替换AlertDialog

    DialogFragment是在Android3.0(API level 11)中引入的,它代替了已经不建议使用的AlertDialog. DialogFragment高效地封装和管理对话框的生命周期 ...

  5. 使用DialogFragment创建对话框总结

    回调Activity中的函数 http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents 在DialogFragme ...

  6. 使用.NET Core中创建Windows服务(一) - 使用官方推荐方式

    原文:Creating Windows Services In .NET Core – Part 1 – The "Microsoft" Way 作者:Dotnet Core Tu ...

  7. 使用.NET Core创建Windows服务(一) - 使用官方推荐方式

    原文:使用.NET Core创建Windows服务(一) - 使用官方推荐方式 原文:Creating Windows Services In .NET Core – Part 1 – The &qu ...

  8. Android代码内存优化建议-Android官方篇

    转自:http://androidperformance.com/ http://developer.android.com/intl/zh-cn/training/displaying-bitmap ...

  9. Android开发——官方推荐使用DialogFragment替换AlertDialog

    )比如当屏幕旋转时,AlertDialog会消失,更不会保存如EditText上的文字,如果处理不当很可能引发异常,因为Activity销毁前不允许对话框未关闭.而DialogFragment对话框会 ...

随机推荐

  1. GJM :C#开发 异步处理是目的,多线程是手段

    但是BeginAccept和EndAccept不就是system.net.socket封装好的异步socket吗如果用多线程来实现的话那就不叫异步了吧 1.再次强调,异步是目的,多线程是手段. 所谓异 ...

  2. 从头开始搭建一个dubbo+zookeeper平台

    本篇主要是来分享从头开始搭建一个dubbo+zookeeper平台的过程,其中会简要介绍下dubbo服务的作用. 首先,看下一般网站架构随着业务的发展,逻辑越来越复杂,数据量越来越大,交互越来越多之后 ...

  3. 寻觅[Getting Answers]

    原文:http://www.mikeash.com/getting_answers.html 作者:mike@mikeash.com 译者:今天早上起床,有幸读到这篇文章,觉得它是我们在这个世界上的基 ...

  4. Web(Jsp+ Servlet)开发中如何解决中文乱码问题

    1.中文乱码的成因 编码的字符集和解码的字符集不一致. 2.web开发过程中可能出现的乱码的位置及解决方案 ①request乱码 在向服务器传递数据时,所传递的中文有可能出现乱码. post请求(协议 ...

  5. .NET 各种框架

    基于.NET平台常用的框架整理 分布式缓存框架: Microsoft Velocity:微软自家分布式缓存服务框架. Memcahed:一套分布式的高速缓存系统,目前被许多网站使用以提升网站的访问速度 ...

  6. 让ABAP开发者更加轻松的若干快捷键

    引言 ABAP是一种和当代编程语言在许多方面有着相当不同的编程语言.ABAP的某些方面可能会让我们奇怪,为什么它会如此复杂?而它的某些方面又是那么杰出,给予了ABAP开发者们比其它任何语言更多的便利. ...

  7. OC 类别与扩展(匿名类别)

    OC 类别与扩展(匿名类别) 类别(Categroy): 又称为扩展类,在类的原基础上扩展方法,且不可添加变量,如果扩展的方法与原始类中的方法相同,则会隐藏原始方法,且不可在扩展方法中通过super调 ...

  8. IOS 日期的简洁格式展示

    首先我要解释一下标题的意义,日期的简洁格式展示,之所以简介,是因为让人一目了然,不需要思考是什么时候. 在详细一点就是我们在微信朋友圈中 所看到的时间格式. 例如:刚刚 -几分钟前-几小时前等等. 今 ...

  9. Android 应用程序集成Google 登录及二次封装

    谷歌登录API:  https://developers.google.com/identity/sign-in/android/ 1.注册并且登录google网站 https://accounts. ...

  10. 比Ansible更吊的自动化运维工具,自动化统一安装部署自动化部署udeploy 1.0 版本发布

    新增功能: 逻辑与业务分离,完美实现逻辑与业务分离,业务实现统一shell脚本开发,由框架统一调用. 并发多线程部署,不管多少台服务器,多少个服务,同时发起线程进行更新.部署.启动. 提高list规则 ...