dialogfragment在android 3.0时被引入。是一种特殊的fragment,用于在activity的内容之上展示一个模态的对话框。典型的用于:展示警告框,输入框,确认框等等。
在dialogfragment产生之前,我们创建对话框:一般采用alertdialog和dialog。注:官方不推荐直接使用dialog创建对话框。
使用dialogfragment来管理对话框,当旋转屏幕和按下后退键时可以更好的管理其声明周期,它和fragment有着基本一致的声明周期。且dialogfragment也允许开发者把dialog作为内嵌的组件进行重用,类似fragment(可以在大屏幕和小屏幕显示出不同的效果)。上面会通过例子展示这些好处~
使用dialogfragment至少需要实现oncreateview或者oncreatedialog方法。oncreateview即使用定义的xml布局文件展示dialog。oncreatedialog即利用alertdialog或者dialog创建出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_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");
效果图:
可以看到,对话框成功创建并显示出来,不过默认对话框有个讨厌的标题,我们怎么去掉呢:可以在oncreateview中调用getdialog().requestwindowfeature(window.feature_no_title);即可去掉。即:
getdialog().requestwindowfeature(window.feature_no_title);
很完美的去掉了讨厌的标题。
在oncreatedialog中一般可以使用alertdialog或者dialog创建对话框,不过既然google不推荐直接使用dialog,我们就使用alertdialog来创建一个登录的对话框。
a)布局文件
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:orientation="vertical" >
<imageview
android:layout_height="64dp"
android:background="#ffffbb33"
android:contentdescription="@string/app_name"
android:scaletype="center"
android:src="@drawable/title" />
android:id="@+id/id_txt_username"
android:layout_marginbottom="4dp"
android:layout_marginleft="4dp"
android:layout_marginright="4dp"
android:layout_margintop="16dp"
android:hint="input username"
android:inputtype="textemailaddress" />
android:id="@+id/id_txt_password"
android:layout_marginbottom="16dp"
android:layout_margintop="4dp"
android:fontfamily="sans-serif"
android:hint="input password"
android:inputtype="textpassword" />
</linearlayout>
b)继承dialogfragment重写oncreatedialog方法
import android.app.alertdialog;
import android.app.dialog;
import android.content.dialoginterface;
import android.widget.edittext;
public class logindialogfragment extends dialogfragment
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的。
从dialog传递数据给activity,可以使用“fragment interface pattern”的方式,下面通过一个改造上面的登录框来展示这种模式。
改动比较小,直接贴代码了:
private edittext musername;
private edittext mpassword;
public interface logininputlistener
void onlogininputcomplete(string username, string password);
musername = (edittext) view.findviewbyid(r.id.id_txt_username);
mpassword = (edittext) view.findviewbyid(r.id.id_txt_password);
logininputlistener listener = (logininputlistener) getactivity();
listener.onlogininputcomplete(musername
.gettext().tostring(), mpassword
.gettext().tostring());
拿到username和password的引用,在点击登录的时候,把activity强转为我们自定义的接口:logininputlistener,然后将用户输入的数据返回。
mainactivity中需要实现我们的接口logininputlistener,实现我们的方法,就可以实现当用户点击登陆时,获得我们的帐号密码了:
c) mainactivity
import com.example.zhy_dialogfragment.logindialogfragment.logininputlistener;
import android.app.activity;
import android.widget.toast;
public class mainactivity extends activity implements logininputlistener
protected void oncreate(bundle savedinstancestate)
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
public void showlogindialog(view view)
public void onlogininputcomplete(string username, string password)
toast.maketext(this, "帐号:" + username + ", 密码 :" + password,
toast.length_short).show();
效果:
我们希望,一个对话框在大屏幕上以对话框的形式展示,而小屏幕上则直接嵌入当前的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
<resources>
<bool name="large_layout">false</bool>
</resources>
然后在res下新建一个values-large,在values-large下再新建一个bools.xml
<bool name="large_layout">true</bool>
最后测试:
左边为模拟器,右边为我的手机~~~~~
当用户输入帐号密码时,忽然旋转了一下屏幕,帐号密码不见了~~~是不是会抓狂
传统的new alertdialog在屏幕旋转时,第一不会保存用户输入的值,第二还会报异常,因为activity销毁前不允许对话框未关闭。而通过dialogfragment实现的对话框则可以完全不必考虑旋转的问题。
我们直接把上面登录使用alertdialog创建的登录框,拷贝到mainactivity中直接调用:
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))
// sign in the user ...
}).setnegativebutton("cancel", null).show();
下面我分别点击两种方式创建的登录框,看效果图:
可以看到,传统的dialog旋转屏幕时就消失了,且后台log会报异常~~~使用dialogfragment则不受影响。
好了,关于dialogfragment的介绍结束~~~~
有任何疑问请留言
<a target="_blank" href="http://download.csdn.net/detail/lmj623565791/7638357">源码点击下载</a>