优雅封装DialogFragment对话框

说明 : 对DialogFragment进行封装 , 代码部分在章节(1.封装代码) , 如何使用请到章节(2.使用)中查看 .

1. 封装代码

自己建个类 , 把直接把代码复制粘贴过去 , 就可以在外部调用了 .

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextPaint;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;

public class MyAlertDialogFragment extends DialogFragment {

    private Context mContext;
    private Activity mActivity = null;
    private Fragment mFragment = null;
    //标题
    private String mTitle = "提示";
    private int mTitleSize = 20;
    private int mTitleColor = R.color.primary_text;
    //内容
    private String mMessage = "暂无内容";
    //按钮
    private String mPositiveBtnStr = "确定";
    private String mNegativeBtnStr = "取消";
    private String mNeutralBtnStr = "";//中立按钮默认无文字
    private int mPositiveBtnColor = R.color.primary;
    private int mNegativeBtnColor = R.color.primary;
    private int mNeutralBtnColor = R.color.secondary_text;
    private int mPositiveBtnStrSize = 14;
    private int mNegativeBtnStrSize = 14;
    private int mNeutralBtnStrSize = 14;
    //背景透明度
    private float mDimAmout = 0.0f;
    //能否点击取消
    private boolean mCancelOutside = true;
    private boolean mCancelBackup = true;

    ///构造/

    /**
     * 用volatile修饰的变量,
     * 线程在每次使用变量的时候,都会读取变量修改后的最的值。
     * volatile很容易被误用,用来进行原子性操作。
     */
    private static volatile MyAlertDialogFragment myAlertDialogFragment = null;

    //私有化构造函数:
    private void PayDialogFragment() {
    }

    /**
     * 单例模式:创建  Fragment:
     *
     * @return
     */
    public static MyAlertDialogFragment getInstance() {
        if (myAlertDialogFragment == null) {
            synchronized (MyAlertDialogFragment.class) {
                if (myAlertDialogFragment == null) {
                    myAlertDialogFragment = new MyAlertDialogFragment();
                }
            }
        }
        return myAlertDialogFragment;
    }

    //activity调用
    //MyAlertDialogFragment editNameDialog = MyAlertDialogFragment.getInstance();
    //                   editNameDialog.show(getFragmentManager(), "PayDialog");

    /setter//


    /**
     * 设置中立按钮文字
     *
     * @param neutralBtnStr 默认:"等等再说"
     * @return
     */
    public MyAlertDialogFragment setNeutralBtnStr(String neutralBtnStr) {
        mNeutralBtnStr = neutralBtnStr;
        return this;
    }

    /**
     * 设置中立按钮颜色
     *
     * @param neutralBtnColor 默认:R.color.secondary_text
     * @return
     */
    public MyAlertDialogFragment setNeutralBtnColor(int neutralBtnColor) {
        mNeutralBtnColor = neutralBtnColor;
        return this;
    }

    /**
     * 设置中立按钮尺寸
     *
     * @param neutralBtnStrSize 默认:14
     * @return
     */
    public MyAlertDialogFragment setNeutralBtnStrSize(int neutralBtnStrSize) {
        mNeutralBtnStrSize = neutralBtnStrSize;
        return this;
    }

    /**
     * 设置能否点击外部取消对话框
     *
     * @param cancelOutside 默认:true 可以取消
     * @return
     */
    public MyAlertDialogFragment setCancelOutside(boolean cancelOutside) {
        mCancelOutside = cancelOutside;
        return this;
    }

    /**
     * 设置能否点击"后退键"取消对话框
     *
     * @param cancelBackup 默认:true 可以取消
     * @return
     */
    public MyAlertDialogFragment setCancelBackup(boolean cancelBackup) {
        mCancelBackup = cancelBackup;
        return this;
    }

    /**
     * 设置标题字号
     *
     * @param titleSize 默认:20
     * @return
     */
    public MyAlertDialogFragment setTitleSize(int titleSize) {
        mTitleSize = titleSize;
        return this;
    }

    /**
     * 设置标题颜色
     *
     * @param titleColor 默认:R.color.primary_text
     * @return
     */
    public MyAlertDialogFragment setTitleColor(int titleColor) {
        mTitleColor = titleColor;
        return this;
    }

    /**
     * 设置积极按钮颜色
     *
     * @param positiveBtnColor 默认:R.color.primary
     * @return
     */
    public MyAlertDialogFragment setPositiveBtnColor(int positiveBtnColor) {
        mPositiveBtnColor = positiveBtnColor;
        return this;
    }

    /**
     * 设置消极按钮颜色
     *
     * @param negativeBtnColor 默认:R.color.primary
     * @return
     */
    public MyAlertDialogFragment setNegativeBtnColor(int negativeBtnColor) {
        mNegativeBtnColor = negativeBtnColor;
        return this;
    }

    /**
     * 设置积极按钮(文字)尺寸
     *
     * @param positiveBtnStrSize 默认:14
     * @return
     */
    public MyAlertDialogFragment setPositiveBtnStrSize(int positiveBtnStrSize) {
        mPositiveBtnStrSize = positiveBtnStrSize;
        return this;
    }

    /**
     * 设置消极按钮(文字)尺寸
     *
     * @param negativeBtnStrSize 默认14
     * @return
     */
    public MyAlertDialogFragment setNegativeBtnStrSize(int negativeBtnStrSize) {
        mNegativeBtnStrSize = negativeBtnStrSize;
        return this;
    }

    /**
     * 设置上下文 context
     *
     * @param context
     * @return
     */
    public MyAlertDialogFragment setContext(Context context) {
        this.mContext = context;
        return this;
    }

    /**
     * activity调用对话框时设置
     *
     * @param activity
     * @return
     */
    public MyAlertDialogFragment setActivity(Activity activity) {
        mActivity = activity;
        return this;
    }

    /**
     * fragment调用对话框时设置
     *
     * @param fragment
     * @return
     */
    public MyAlertDialogFragment setFragment(Fragment fragment) {
        mFragment = fragment;
        return this;
    }

    /**
     * 编写标题文字
     *
     * @param title 默认:"提示"
     * @return
     */
    public MyAlertDialogFragment setTitle(String title) {
        this.mTitle = title;
        return this;
    }

    /**
     * 设置对话框弹出背景透明度
     *
     * @param dimAmout 不透明程度 0.0f(透明)-1.0f(不透明)
     * @return
     */
    public MyAlertDialogFragment setDimAmout(float dimAmout) {
        this.mDimAmout = dimAmout;
        return this;
    }

    /**
     * 编写内容文字
     *
     * @param message 默认为空
     * @return
     */
    public MyAlertDialogFragment setMessage(String message) {
        this.mMessage = message;
        return this;
    }

    /**
     * 编写积极按钮文字
     *
     * @param positiveBtnStr 默认:"确定"
     * @return
     */
    public MyAlertDialogFragment setPositiveBtnStr(String positiveBtnStr) {
        this.mPositiveBtnStr = positiveBtnStr;
        return this;
    }

    /**
     * 编写消极按钮文字
     *
     * @param negativeBtnStr 默认:"取消"
     * @return
     */
    public MyAlertDialogFragment setNegativeBtnStr(String negativeBtnStr) {
        this.mNegativeBtnStr = negativeBtnStr;
        return this;
    }

    

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final AlertDialog mAlertDialog = new AlertDialog.Builder(getActivity(), R.style.mAlertDialogStyle)
                .setCustomTitle(this.customTitle(getActivity(), mTitle, mTitleSize, mTitleColor, false))
                .setMessage(mMessage)
                .setPositiveButton(mPositiveBtnStr, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //监听回调
                        if (mFragment != null) {
                            MyAlertDialogFragmentInterface positiveBtnCallback = (MyAlertDialogFragmentInterface) mFragment;
                            positiveBtnCallback.doPositive();
                            dismiss();
                        }

                        if (mActivity != null) {
                            MyAlertDialogFragmentInterface positiveBtnCallback = (MyAlertDialogFragmentInterface) mActivity;
                            positiveBtnCallback.doPositive();
                            dismiss();
                        }

                    }
                })
                .setNegativeButton(mNegativeBtnStr, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //监听回调
                        if (mFragment != null) {
                            MyAlertDialogFragmentInterface negativeBtnCallback = (MyAlertDialogFragmentInterface) mFragment;
                            negativeBtnCallback.doNegative();
                            dismiss();
                        }

                        if (mActivity != null) {
                            MyAlertDialogFragmentInterface negativeBtnCallback = (MyAlertDialogFragmentInterface) mActivity;
                            negativeBtnCallback.doNegative();
                            dismiss();
                        }
                    }
                })
                .setNeutralButton(mNeutralBtnStr, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //监听回调
                        if (mFragment != null) {
                            MyAlertDialogFragmentInterface negativeBtnCallback = (MyAlertDialogFragmentInterface) mFragment;
                            negativeBtnCallback.doNeutral();
                            dismiss();
                        }

                        if (mActivity != null) {
                            MyAlertDialogFragmentInterface negativeBtnCallback = (MyAlertDialogFragmentInterface) mActivity;
                            negativeBtnCallback.doNeutral();
                            dismiss();
                        }
                    }
                })
                //.setNeutralButton(mNegativeBtnStr, null)
                .create();

        //禁止点击 dialog 外部取消弹窗
        mAlertDialog.setCanceledOnTouchOutside(mCancelOutside);

        //设置这个对话框不能被用户按[返回键]而取消掉
        if (!mCancelBackup) {
            mAlertDialog.setCancelable(false);//设置这个对话框不能被用户按[返回键]而取消掉
            mAlertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                //这里的setOnKeyListener作用就是屏蔽用户按下KeyEvent.KEYCODE_SEARCH
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    return (keyCode == KeyEvent.KEYCODE_SEARCH);
                }
            });
        }

        //先判断是否在前台
        if (!this.isAppToBackground(getActivity())) {
            mAlertDialog.show();
            mAlertDialog.getWindow().setAttributes(
                    this.getLayoutParamsForDimAmount(mAlertDialog, mDimAmout));
        }

        //注意:这里这些属性的获取都一定是要在Dialog调用完show()方法之后,即Dialog展示出来之后。要不就会NullPointException。
        this.setDialogButtonAll(mAlertDialog, getActivity(),
                mPositiveBtnColor, mPositiveBtnStrSize,
                mNegativeBtnColor, mNegativeBtnStrSize,
                mNeutralBtnColor, mNeutralBtnStrSize);

        return mAlertDialog;
    }

    public interface MyAlertDialogFragmentInterface {
        /**
         * 点击positive按钮的回调
         */
        void doPositive();

        /**
         * 点击negative按钮的回调
         */
        void doNegative();

        /**
         * 点击neutral按钮的回调
         */
        void doNeutral();
    }



    ///工具方法/

    /**
     * 设置LayoutParams的dimAmount属性
     * <br>dimAmount在0.0f和1.0f之间,0.0f完全不暗,即背景是可见的,1.0f时候,背景全部变黑暗。
     *
     * @param dimAmout 不透明程度 0.0f(透明)-1.0f(不透明)
     * @return
     */
    @NonNull
    private WindowManager.LayoutParams getLayoutParamsForDimAmount(Dialog alertDialog, float dimAmout) {
        //设置弹出对话框背景变暗程度
        WindowManager.LayoutParams layoutParams = alertDialog.getWindow().getAttributes();
        //在show()方法后面设置dimAmount属性,才会生效。进度条也是。
        layoutParams.dimAmount = dimAmout;
        return layoutParams;
    }


    /**
     * 判断当前应用程序(如Activity)处于前台还是后台 (可见/不可见)
     * return false 在前台
     * return true 在后台
     */
    private boolean isAppToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 设置按钮字体颜色,字体大小
     *
     * @param alertDialog
     * @param posColor     积极按钮
     * @param posSize
     * @param negColor     消极按钮
     * @param negSize
     * @param neutralColor 中立按钮
     * @param neutralSize
     */
    private void setDialogButtonAll(AlertDialog alertDialog, Context context,
                                          int posColor, int posSize,
                                          int negColor, int negSize,
                                          int neutralColor, int neutralSize) {

        Button btnPositive =
                alertDialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE);
        Button btnNegative =
                alertDialog.getButton(android.app.AlertDialog.BUTTON_NEGATIVE);
        Button btnNeutral =
                alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL);

        if (btnPositive != null) {
            btnPositive.setTextColor(context.getResources().getColor(posColor));
            btnPositive.setTextSize(posSize);
        }

        if (btnNegative != null) {
            btnNegative.setTextColor(context.getResources().getColor(negColor));
            btnNegative.setTextSize(negSize);
        }

        if (btnNeutral != null) {
            btnNeutral.setTextColor(context.getResources().getColor(neutralColor));
            btnNeutral.setTextSize(neutralSize);
        }
    }

    /**
     * 设置自定义title
     *
     * @param context
     * @param title
     * @param size
     * @param color
     * @param bold    是否粗体
     * @return
     */
    private View customTitle(Context context, String title, int size, int color, boolean bold) {
        //自定义标题
        TextView mDialogTitle = new TextView(context);
        mDialogTitle.setText(title);    //内容
        mDialogTitle.setTextSize(size);//字体大小
        mDialogTitle.setPadding(64, 64, 64, 48);//位置-->int left, int top, int right, int bottom
        mDialogTitle.setTextColor(context.getResources().getColor(color));//颜色

        TextPaint tp = mDialogTitle.getPaint();
        tp.setFakeBoldText(bold);

        return mDialogTitle;
    }

}

2. 使用

1. Activity 实现接口并声明DialogFragment
public class MainActiviy extend Activity
        implements  MyAlertDialogFragment.MyAlertDialogFragmentInterface {

        private MyAlertDialogFragment mMyAlertDialogFragment;
        ...
}
2. DialogFragment实例化
    mMyAlertDialogFragment = MyAlertDialogFragment.getInstance();
    if (!mMyAlertDialogFragment.isAdded()) {
        mMyAlertDialogFragment
                .setActivity(MainActiviy.this)
                .setTitle("退出登录")
                .setMessage("请问您是否退出系统?")
                .setPositiveBtnStr("是的")
                .setNegativeBtnStr("下次吧")
                .show(MainActiviy.this.getSupportFragmentManager(), "退出");
    }
3. 业务逻辑在回调方法中实现
 @Override
public void doPositive() {
    if (mMyAlertDialogFragmentTips == null && mMyAlertDialogFragment != null && mMyAlertDialogFragment.getDialog() != null && mMyAlertDialogFragment.getDialog().isShowing()) {
        this.finish();
    }
}

@Override
public void doNegative() {

}

@Override
public void doNeutral() {

}
4. 多个DialogFragment的判断

在实例化一个DialogFragment之前,先确保其他DialogFragment已被销毁(null)

if (mDialogFragment2 != null) {
        mDialogFragment2.dismiss();
        mDialogFragment2 = null;
    }

    mDialogFragment = MyAlertDialogFragment.getInstance();
    if (!mDialogFragment.isAdded()) {
        mDialogFragment
                .setActivity(MainActiviy.this)
                .setTitle("退出登录")
                .setMessage("请问您是否要退出系统?")
                .setPositiveBtnStr("是的")
                .setNegativeBtnStr("下次吧")
                .show(MainActiviy.this.getSupportFragmentManager(), "退出");
        }

在回调接口中,进行判断 :
其他DialogFragment已经被销毁 且需要使用的DialogFragment正在显示中

@Override
public void doPositive() {
    if (
    mMyAlertDialogFragmentTips == null && 
    mMyAlertDialogFragment != null &&
    mMyAlertDialogFragment.getDialog() != null &&
    mMyAlertDialogFragment.getDialog().isShowing()) 
    {
        ...   
    }
}

@Override
public void doNegative() {

}

@Override
public void doNeutral() {

}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值