DialogFragment对话框出现的意义 DialogFragment是在Android3.0(API level 11)中引入的,它代替了已经不建议使用的AlertDialog。
  • 它和Fragment基本一致的生命周期,因此便于Activity更好的控制管理DialogFragment。
  • DialogFragment的出现完美的解决了横竖屏幕切换Dialog消失的问题。
  • 管理自定义的Dialog和系统原生的Dialog麻烦


DialogFragment怎么解决Dialog存在的问题:
  • DialogFragment说到底还是一个Fragment,因此它继承了Fragment的所有特性。同理FragmentManager会管理DialogFragment。在手机配置发生变化的时候,FragmentManager可以负责现场的恢复工作。调用DialogFragment的setArguments(bundle)方法进行数据的设置,可以保证DialogFragment的数据也能恢复。

  • DialogFragment里的onCreateView和onCreateDIalog 2个方法,onCreateView可以用来创建自定义Dialog,onCreateDIalog 可以用Dialog来创建系统原生Dialog。可以在一个类中管理2种不同的dialog。



onCreateDialog方法创建
MainActivity.java packageexample.abe.com.dialogframgent ;

importandroid.os.Bundle ;
importandroid.support.v4.app.DialogFragment ;
importandroid.support.v4.app.FragmentManager ;
importandroid.support.v7.app.AppCompatActivity ;
importandroid.view.View ;
importandroid.widget.Button ;

publicclassMainActivity extendsAppCompatActivity implementsAlertDialogFragment.NoticeDialogListener{

privatestaticString DIALOG_FRAGMENT= "dialogFragment" ;

@Override
protectedvoid onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main) ;

Buttonbutton=(Button)findViewById(R.id. button) ;
button.setOnClickListener( newView.OnClickListener(){
@Override
publicvoid onClick(Viewv){
showDialogFragment() ;
}
}) ;
}

/**
*Action
*/
publicvoid showDialogFragment(){

FragmentManagerfragmentManager=getSupportFragmentManager() ;
DialogFragmentfragment=(DialogFragment)fragmentManager.findFragmentByTag( DIALOG_FRAGMENT) ;
if(fragment!= null){
fragment.dismiss() ;
}
AlertDialogFragmentdialogFragment=AlertDialogFragment
. newInstance( DIALOG_FRAGMENT ,android.R.style. Theme_Material_Dialog , "标题" , "信息" , "确定" , "取消") ;
dialogFragment.show(fragmentManager , DIALOG_FRAGMENT) ;
}

/**
*implement
*/
publicvoid onDialogPositiveClick(DialogFragmentdialog){
System. out.println( "onDialogPositiveClick") ;
}

publicvoid onDialogNegativeClick(DialogFragmentdialog){
System. out.println( "onDialogNegativeClick") ;
}
}


AlertDialogFragment.java packageexample.abe.com.dialogframgent ;

importandroid.app.Activity ;
importandroid.app.AlertDialog ;
importandroid.app.Dialog ;
importandroid.content.DialogInterface ;
importandroid.os.Bundle ;
importandroid.support.v4.app.DialogFragment ;

/**
*Createdbyabeon16/4/13.
*/
publicclassAlertDialogFragment extendsDialogFragment{

//Usethisinstanceoftheinterfacetodeliveractionevents
NoticeDialogListener mListener ;

publicstaticAlertDialogFragment newInstance(Stringtag ,intthemeResId ,Stringtitle ,Stringmessage ,
StringpositiveButtonTitle ,StringnegativeButtonTitle){
AlertDialogFragmentfrag= newAlertDialogFragment() ;
Bundleargs= newBundle() ;
args.putInt( "themeResId" ,themeResId) ;
args.putString( "title" ,title) ;
args.putString( "tag" ,tag) ;
args.putString( "message" ,message) ;
args.putString( "positiveButtonTitle" ,positiveButtonTitle) ;
args.putString( "negativeButtonTitle" ,negativeButtonTitle) ;
frag.setArguments(args) ;
returnfrag ;
}

@Override
publicDialog onCreateDialog(BundlesavedInstanceState){
intthemeResId=getArguments().getInt( "themeResId") ;
Stringtitle=getArguments().getString( "title") ;
Stringmessage=getArguments().getString( "message") ;
StringpositiveButtonTitle=getArguments().getString( "positiveButtonTitle") ;
StringnegativeButtonTitle=getArguments().getString( "negativeButtonTitle") ;
returnnewAlertDialog.Builder(getActivity() ,themeResId)
.setTitle(title)
.setMessage(message)
.setPositiveButton(positiveButtonTitle ,newDialogInterface.OnClickListener(){

@Override
publicvoid onClick(DialogInterfacedialog ,intwhich){
mListener.onDialogPositiveClick(AlertDialogFragment. this) ;
dismiss() ;
}
})
.setNegativeButton(negativeButtonTitle ,newDialogInterface.OnClickListener(){

@Override
publicvoid onClick(DialogInterfacedialog ,intwhich){
mListener.onDialogNegativeClick(AlertDialogFragment. this) ;
dismiss() ;
}
})
.create() ;
}

@Override
publicvoid onAttach(Activityactivity){
super.onAttach(activity) ;
try{
mListener=(NoticeDialogListener)activity ;
} catch(ClassCastExceptione){
thrownewClassCastException(activity.toString()
+ "mustimplementNoticeDialogListener") ;
}
}

/**
*Get&Set
*/
publicNoticeDialogListener getmListener(){
return mListener ;
}

/**
*监听类
*/
publicinterfaceNoticeDialogListener{
void onDialogPositiveClick(DialogFragmentdialog) ;
void onDialogNegativeClick(DialogFragmentdialog) ;
}
}

效果图:


onCreateView创建
MainActivity.java packageexample.abe.com.dialogframgent ;

importandroid.os.Bundle ;
importandroid.support.v4.app.DialogFragment ;
importandroid.support.v4.app.Fragment ;
importandroid.support.v4.app.FragmentManager ;
importandroid.support.v4.app.FragmentTransaction ;
importandroid.support.v7.app.AppCompatActivity ;
importandroid.view.View ;
importandroid.widget.Button ;

publicclassMainActivity extendsAppCompatActivity implementsMyDialogFragment.NoticeDialogListener{

privatestaticString DIALOG_FRAGMENT= "dialogFragment" ;

@Override
protectedvoid onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main) ;

Buttonbutton=(Button)findViewById(R.id. button) ;
button.setOnClickListener( newView.OnClickListener(){
@Override
publicvoid onClick(Viewv){
showDialog() ;
}
}) ;
}

/**
*Action
*/
void showDialog(){

FragmentTransactionft=getSupportFragmentManager().beginTransaction() ;
Fragmentprev=getSupportFragmentManager().findFragmentByTag( "dialog") ;
if(prev!= null){
ft.remove(prev) ;
}
ft.addToBackStack( null) ;
DialogFragmentnewFragment=MyDialogFragment. newInstance(DialogFragment. STYLE_NO_TITLE) ;
newFragment.show(ft , "dialog") ;
}

/**
*implement
*/
publicvoid onDialogClick(DialogFragmentdialog){
System. out.println( "onDialogClick") ;
}
}


MyDialogFragment.java packageexample.abe.com.dialogframgent ;

importandroid.app.Activity ;
importandroid.app.Dialog ;
importandroid.os.Bundle ;
importandroid.support.v4.app.DialogFragment ;
importandroid.view.LayoutInflater ;
importandroid.view.View ;
importandroid.view.ViewGroup ;
importandroid.view.Window ;
importandroid.widget. Button ;

publicclassMyDialogFragment extendsDialogFragment{

NoticeDialogListener mListener ;

staticMyDialogFragment newInstance( intnum){
MyDialogFragmentf= newMyDialogFragment() ;

Bundleargs= newBundle() ;
args.putInt( "num" ,num) ;
f.setArguments(args) ;

returnf ;
}

@Override
publicvoid onAttach(Activityactivity){
super.onAttach(activity) ;
try{
mListener=(NoticeDialogListener)activity ;
} catch(ClassCastExceptione){
thrownewClassCastException(activity.toString()
+ "mustimplementNoticeDialogListener") ;
}
}

@Override
publicView onCreateView(LayoutInflaterinflater ,ViewGroupcontainer ,
BundlesavedInstanceState){
Viewv=inflater.inflate(R.layout. fragment_dialog ,container ,false) ;

Buttonbutton=( Button)v.findViewById(R.id. show) ;
button.setOnClickListener( newView.OnClickListener(){
publicvoid onClick(Viewv){
mListener.onDialogClick(MyDialogFragment. this) ;
dismiss() ;
}
}) ;

returnv ;
}

@Override
publicDialog onCreateDialog(BundlesavedInstanceState){
//TheonlyreasonyoumightoverridethismethodwhenusingonCreateView()is
//tomodifyanydialogcharacteristics.Forexample,thedialogincludesa
//titlebydefault,butyourcustomlayoutmightnotneedit.Sohereyoucan
//removethedialogtitle,butyoumustcallthesuperclasstogettheDialog.
Dialogdialog= super.onCreateDialog(savedInstanceState) ;
dialog.requestWindowFeature(Window. FEATURE_NO_TITLE) ;
returndialog ;
}

/**
*Get&Set
*/
publicNoticeDialogListener getmListener(){
return mListener ;
}

/**
*监听类
*/
publicinterfaceNoticeDialogListener{
void onDialogClick(DialogFragmentdialog) ;
}
}
效果图:



活学活用 MainActivity.java publicclassMainActivity extendsAppCompatActivity{

@Override
protectedvoid onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main) ;

ButtonbtnDialog=(Button)findViewById(R.id. button_dialog) ;
btnDialog.setOnClickListener( newView.OnClickListener(){
@Override
publicvoid onClick(Viewv){
FragmentManagerfragmentManager=getSupportFragmentManager() ;
MyDialogFragmentmyDialog= newMyDialogFragment() ;
myDialog.show(fragmentManager , "DIALOG_FRAGMENT") ;
}
}) ;
}
}
MyDialogFragment.java publicclassMyDialogFragment extendsDialogFragment{

@Override
publicDialog onCreateDialog(BundlesavedInstanceState){
LayoutInflaterinflater=LayoutInflater. from(getContext()) ;
Viewview=inflater.inflate(R.layout. fragment_dialog ,null) ;
Dialogdialog= newDialog(getContext() ,R.style. my_dialog) ;
dialog.setContentView(view) ;
WindowdialogWindow=dialog.getWindow() ;
dialogWindow.setGravity(Gravity. CENTER) ;
dialogWindow.setWindowAnimations(R.style. anim_slide_from_buttom) ;
returndialog ;
}
}

Layout布局视图
<?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"    android:background="@android:color/transparent">    <LinearLayout        android:layout_marginTop="25dp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="@drawable/shape_rounded_input_white"        android:orientation="vertical">        <TextView            android:layout_width="match_parent"            android:layout_height="20dp"            android:layout_marginTop="34dp"            android:gravity="center_horizontal|top"            android:text="小通知"            android:textColor="#444444"            android:textSize="17sp" />        <TextView            android:layout_width="match_parent"            android:layout_height="18dp"            android:layout_marginTop="17dp"            android:gravity="center"            android:text="自定义通知好奇怪"            android:textColor="#444444"            android:textSize="16sp" />        <View            android:layout_width="match_parent"            android:layout_height="1dp"            android:layout_marginTop="10dp"            android:background="#b2b2b2" />        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal"            android:padding="0dp">            <Button                android:id="@+id/btn_cancel"                android:layout_width="0dp"                android:layout_height="40dp"                android:layout_weight="1"                android:background="#00ffffff"                android:text="奇怪"                android:textColor="#444444" />            <View                android:id="@+id/postCancelBtnDivider"                android:layout_width="1dp"                android:layout_height="match_parent"                android:background="#b2b2b2" />            <Button                android:id="@+id/btn_ok"                android:layout_width="0dp"                android:layout_height="40dp"                android:layout_weight="1"                android:background="#00000000"                android:text="不奇怪"                android:textColor="#007aff" />        </LinearLayout>    </LinearLayout>    <ImageView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="#00ffffff"        android:scaleType="fitCenter"        android:src="@mipmap/ic_launcher" /></RelativeLayout>

最关键的Dialog Style Dialog的style主题设置是最重要的!!! <!--透明背景弹框-->
<style name= "my_dialog" parent= "@android:style/Theme.Dialog" >
<item name= "android:windowFrame" >@null </item>
<item name= "android:windowIsFloating" >true </item>
<item name= "android:windowIsTranslucent" >true </item>
<item name= "android:windowNoTitle" >true </item>
<item name= "android:backgroundDimEnabled" >true </item>
<item name= "android:windowBackground" >@android:color/transparent </item>
</style>

<!--底部滑入滑出动画-->
<style name= "anim_slide_from_buttom" >
<item name= "android:windowEnterAnimation" >@anim/slide_in_from_buttom </item>
<item name= "android:windowExitAnimation" >@anim/slide_out_from_buttom </item>
</style>

效果图:

参考: http://developer.android.com/intl/zh-cn/guide/topics/ui/dialogs.html
http://developer.android.com/intl/zh-cn/reference/android/app/DialogFragment.html
http://www.cnblogs.com/and_he/archive/2011/09/16/2178716.html

更多相关文章

  1. [Android实例] android登录Web以及登录保持,cookie管理相关
  2. android小特效(持续更新...)
  3. 最全面的Android(安卓)Studio使用教程(图文)
  4. android中创建XML
  5. (4.1.24.1)Android中Dialog的使用
  6. Acitivity加载模式说起
  7. [置顶] android性能测试工具之dumpsys
  8. Android与Flutter桥接指南
  9. Android(安卓)数据库创建字段时的数据类型

随机推荐

  1. ImageView的属性android:scaleType
  2. 【Android】性能优化的一些方法
  3. android 让一个控件按钮居于底部的几种方
  4. android studio 报Error:failed to find
  5. Maven + Eclipse + Android(安卓)环境搭
  6. [android]实现拖动效果
  7. Android(安卓)UI系列-----RelativeLayout
  8. Android(安卓)screenOrientation 屏幕方
  9. Android(安卓)3.0 r1 API中文文档(107)
  10. Android实用小技巧