转于: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
相关推荐
在Activity中,可以通过`newInstance()`静态方法创建DialogFragment实例,然后调用`show()`方法来显示对话框: ```java CustomDialogFragment dialogFragment = CustomDialogFragment.newInstance(); ...
下面将详细讲解如何基于DialogFragment创建对话框。 首先,我们需要创建一个继承自DialogFragment的类,如这里的`MyAlertDialogFragment`。在这个类中,我们通常会提供一个静态工厂方法`newInstance`,用于初始化...
- 使用`AlertDialog.Builder`类创建对话框,并设置标题、消息、确认按钮和取消按钮的文本。 3. **添加多选列表**: - 使用`AlertDialog.Builder`的`setMultiChoiceItems`方法,传入一个字符串数组作为可选项,一...
在本文中,我们将深入探讨如何使用DialogFragment创建对话框,并通过一个实例来演示其工作原理。 首先,DialogFragment是一个Fragment的子类,因此它拥有Fragment的所有特性。这意味着它可以独立于Activity存在,有...
综上所述,`Android`中的`DialogFragment`是实现交互式对话框的强大工具,它允许开发者创建自定义的界面并轻松地集成到应用程序中。通过理解其生命周期、样式和交互处理,我们可以构建出符合应用需求的高效对话框,...
### 创建对话框 1. **默认对话框**:通过继承`DialogFragment`类并重写`onCreateDialog()`方法来创建一个基本的对话框。 ```java public class MyDialogFragment extends DialogFragment { @Override public ...
DialogFragment是Android SDK提供的一种用于管理对话框的组件,它结合了Fragment的功能,使得对话框可以拥有自己的生命周期,并且可以像其他Fragment一样在Activity之间管理。在本文中,我们将深入探讨如何使用...
1. 创建DialogFragment子类:首先,我们需要创建一个继承自DialogFragment的自定义类,并重写必要的方法,如`onCreateDialog()`,在这个方法中创建并返回一个AlertDialog实例。 ```java public class ...
2. **DialogFragment**:它是Android支持库中的一个类,继承自Fragment,用于展示对话框。与传统Dialog相比,DialogFragment更易于管理,因为它可以参与到Fragment的生命周期管理中,避免了Activity与Dialog之间的...
在Android开发中,DialogFragment和AlertDialog是两种常用的用于展示弹出式对话框的组件。本文将深入探讨这两种组件,以及它们之间的区别,并提供一个实际的示例来帮助理解。 首先,我们来了解一下DialogFragment。...
这是Android中最常见的对话框类型,通过`DialogFragment`或`AlertDialog`实现。 4. **非模态对话框(Non-Modal Dialogs)** - 非模态对话框不会阻止用户与主界面交互,它们更像是浮动视图。例如,使用`PopupWindow...
在Android开发中,有时我们需要创建一个可自定义的弹出窗口来展示信息,这通常可以通过使用`DialogFragment`实现。`DialogFragment`是Android提供的一个类,它扩展了`Fragment`,并添加了对话框样式的特性。在这个...
在Android应用开发中,全局对话框(Global ...综上所述,"android全局对话框dhk.rar"可能提供了一种实现全局对话框的方法,通过学习和应用这些知识点,开发者可以创建出适应各种场景的全局对话框,提高应用的用户体验。
本教程将深入讲解如何在Android系统中创建和使用标准对话框以及自定义对话框。 首先,Android系统提供了几种内置的对话框类型,包括AlertDialog、ProgressDialog、DatePickerDialog、TimePickerDialog等。这些...
例如,创建一个简单的模态确认对话框: ```java AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("确认操作"); builder.setMessage("你确定要执行此操作吗?"); builder....
在Android应用开发中,`DialogFragment`是对话框的一个组件,它是`Fragment`的一个子类,可以方便地在Activity中展示对话框样式的通知或交互。`DialogFragment`提供了与用户进行交互的方式,同时保持了与Android碎片...
本示例主要关注`Android`中的几种基本对话框类型:普通AlertDialog、列表对话框(ListDialog)、进度对话框(ProgressDialog)以及自定义对话框,通过实例来阐述如何在代码中实现它们。 首先,我们来看`AlertDialog...