Android-DialogFragment快速指南

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
package example.abe.com.dialogframgent ;

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

public class MainActivity  extends AppCompatActivity  implements AlertDialogFragment.NoticeDialogListener {

    private static String  DIALOG_FRAGMENT "dialogFragment" ;

    @Override
    protected void  onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState) ;
        setContentView(R.layout. activity_main) ;

        Button button = (Button) findViewById(R.id. button) ;
        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void  onClick(View v) {
                showDialogFragment() ;
            }
        }) ;
    }

    /**
     * Action
     */
    public void  showDialogFragment() {

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

    /**
     * implement
     */
    public void  onDialogPositiveClick(DialogFragment dialog) {
        System. out.println( "onDialogPositiveClick") ;
    }

    public void  onDialogNegativeClick(DialogFragment dialog) {
        System. out.println( "onDialogNegativeClick") ;
    }
}


AlertDialogFragment.java
package example.abe.com.dialogframgent ;

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

/**
 * Created by abe on 16/4/13.
 */
public class AlertDialogFragment  extends DialogFragment {

    // Use this instance of the interface to deliver action events
    NoticeDialogListener  mListener ;

    public static AlertDialogFragment  newInstance(String tag , int themeResId String title String message ,
                                                  String positiveButtonTitle String negativeButtonTitle) {
        AlertDialogFragment frag =  new AlertDialogFragment() ;
        Bundle args =  new Bundle() ;
        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) ;
        return frag ;
    }

    @Override
    public Dialog  onCreateDialog(Bundle savedInstanceState) {
        int themeResId = getArguments().getInt( "themeResId") ;
        String title = getArguments().getString( "title") ;
        String message = getArguments().getString( "message") ;
        String positiveButtonTitle = getArguments().getString( "positiveButtonTitle") ;
        String negativeButtonTitle = getArguments().getString( "negativeButtonTitle") ;
        return new AlertDialog.Builder(getActivity() themeResId)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(positiveButtonTitle , new DialogInterface.OnClickListener() {

                    @Override
                    public void  onClick(DialogInterface dialog , int which) {
                        mListener.onDialogPositiveClick(AlertDialogFragment. this) ;
                        dismiss() ;
                    }
                })
                .setNegativeButton(negativeButtonTitle ,new DialogInterface.OnClickListener() {

                    @Override
                    public void  onClick(DialogInterface dialog , int which) {
                        mListener.onDialogNegativeClick(AlertDialogFragment. this) ;
                        dismiss() ;
                    }
                })
                .create() ;
    }

    @Override
    public void  onAttach(Activity activity) {
        super.onAttach(activity) ;
        try {
            mListener = (NoticeDialogListener) activity ;
       catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    +  " must implement NoticeDialogListener") ;
        }
    }

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

    /**
     * 监听类
     */
    public interface NoticeDialogListener {
        void  onDialogPositiveClick(DialogFragment dialog) ;
        void  onDialogNegativeClick(DialogFragment dialog) ;
    }
}

效果图:



onCreateView创建

MainActivity.java
package example.abe.com.dialogframgent ;

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

public class MainActivity  extends AppCompatActivity  implements MyDialogFragment.NoticeDialogListener {

    private static String  DIALOG_FRAGMENT "dialogFragment" ;

    @Override
    protected void  onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState) ;
        setContentView(R.layout. activity_main) ;

        Button button = (Button) findViewById(R.id. button) ;
        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void  onClick(View v) {
                showDialog() ;
            }
        }) ;
    }

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

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

    /**
     * implement
     */
    public void  onDialogClick(DialogFragment dialog){
        System. out.println( "onDialogClick") ;
    }
}


MyDialogFragment.java
package example.abe.com.dialogframgent ;

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

public class MyDialogFragment  extends DialogFragment {

    NoticeDialogListener  mListener ;

    static MyDialogFragment  newInstance( int num) {
        MyDialogFragment f =  new MyDialogFragment() ;

        Bundle args =  new Bundle() ;
        args.putInt( "num" num) ;
        f.setArguments(args) ;

        return f ;
    }

    @Override
    public void  onAttach(Activity activity) {
        super.onAttach(activity) ;
        try {
            mListener = (NoticeDialogListener) activity ;
       catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    +  " must implement NoticeDialogListener") ;
        }
    }

    @Override
    public View  onCreateView(LayoutInflater inflater ViewGroup container ,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout. fragment_dialog container , false) ;

        Button button = ( Button) v.findViewById(R.id. show) ;
        button.setOnClickListener( new View.OnClickListener() {
            public void  onClick(View v) {
                mListener.onDialogClick(MyDialogFragment. this) ;
                dismiss() ;
            }
        }) ;

        return v ;
    }

    @Override
    public Dialog  onCreateDialog(Bundle savedInstanceState) {
        // The only reason you might override this method when using onCreateView() is
        // to modify any dialog characteristics. For example, the dialog includes a
        // title by default, but your custom layout might not need it. So here you can
        // remove the dialog title, but you must call the superclass to get the Dialog.
        Dialog dialog =  super.onCreateDialog(savedInstanceState) ;
        dialog.requestWindowFeature(Window. FEATURE_NO_TITLE) ;
        return dialog ;
    }

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

    /**
     * 监听类
     */
    public interface NoticeDialogListener {
        void  onDialogClick(DialogFragment dialog) ;
    }
}

效果图:




活学活用
MainActivity.java
public class MainActivity  extends AppCompatActivity {

    @Override
    protected void  onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState) ;
        setContentView(R.layout. activity_main) ;

        Button btnDialog = (Button) findViewById(R.id. button_dialog) ;
        btnDialog.setOnClickListener( new View.OnClickListener() {
            @Override
            public void  onClick(View v) {
                FragmentManager fragmentManager = getSupportFragmentManager() ;
                MyDialogFragment myDialog =  new MyDialogFragment() ;
                myDialog.show(fragmentManager "DIALOG_FRAGMENT") ;
            }
        }) ;
    }
}

MyDialogFragment.java
public class MyDialogFragment  extends DialogFragment {

    @Override
    public Dialog  onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = LayoutInflater. from(getContext()) ;
        View view = inflater.inflate(R.layout. fragment_dialog , null) ;
        Dialog dialog =  new Dialog(getContext() R.style. my_dialog) ;
        dialog.setContentView(view) ;
        Window dialogWindow = dialog.getWindow() ;
        dialogWindow.setGravity(Gravity. CENTER) ;
        dialogWindow.setWindowAnimations(R.style. anim_slide_from_buttom) ;
        return dialog ;
    }
}

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

你可能感兴趣的:(android,android,3.0,对话框)