Android Dialog相关

一、Dialog


Android弹窗在应用中是经常出现的一个组件,当系统需要弹出一个消息和提示的时候就需要用到一个弹窗进行提示。首先了解一下什么是弹窗

android官方文档对Dialog的介绍

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.
dialog就是一个在屏幕上弹出一个可以让用户做出一个选择,或者输入额外的信息的对话框,一个对话框并不会沾满我们整个的屏幕,并且通常用于模型事件当中需要用户做出一个决定后才会继续执行。

Dialog类是dialog对话框的基类,但是我们应该避免直接使用这个类来实例化一个dialog对话框,我们应当使用其子类来得到一个对话框:

java.lang.Object
↳ android.app.Dialog
Known Direct Subclasses
AlertDialog, CharacterPickerDialog, MediaRouteChooserDialog, MediaRouteControllerDialog, Presentation
Known Indirect Subclasses
DatePickerDialog, ProgressDialog, TimePickerDialog

以上Dialog的子类对应的是不同功能的弹窗,可以根据自己的需要进行选择使用,比如DatePickerDialog可以调用系统自带的时间选择弹窗,选择自己需要的样式进行显示,选择时间后可以对选择的日期进行操作。其他的弹窗也是一样的用法。

二、自定义Dialog


有时候可能自带的Dialog并不能满足特定的样式需求,这时候就可以进行自定义Dialog,通过继承Dialog基类进行自定义。


固定样式的弹窗

下面以一个简单的弹窗样式进行自定义操作:

public class NoticeDialog extends Dialog implements View.OnClickListener {

    private TextView mTvTitle;
    private TextView mTvContent;
    private Button mBtnCancel;
    private Button mBtnConfirm;
    private Button mBtnConfirmCenter;

    private String title;
    private String content;
    private String cancel;
    private String confirm;

    private int dialogType;
    /**
     * 弹窗类型为有确认和取消按钮
     */
    public static final int NOTICE_DIALOG = 0;
    /**
     * 弹窗类型为只有确认按钮,用于清除缓存成功提示弹窗
     */
    public static final int CONFIRM_DIALOG = 1;

    private OnCancelClickListener cancelClickListener;
    private OnConfirmClickListener confirmClickListener;

    public interface OnConfirmClickListener {
        /**
         * 点击确认按钮
         */
        void onConfirmClick();
    }

    public interface OnCancelClickListener {
        /**
         * 点击取消按钮
         */
        void onCancelClick();
    }

    public void setOnCancelClickListener(OnCancelClickListener cancelClickListener) {
        this.cancelClickListener = cancelClickListener;
    }

    public void setOnConfirmClickListener(OnConfirmClickListener confirmClickListener) {
        this.confirmClickListener = confirmClickListener;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.app_layout_notice_dialog);
        initView ();
        initData ();
    }

    public NoticeDialog(@NonNull Context context) {
        super (context, R.style.CustomDialog);
    }

    public NoticeDialog(@NonNull Context context,String title, String content, String cancel, String confirm, int dialogType) {
        super (context, R.style.CustomDialog);
        this.title = title;
        this.content = content;
        this.cancel = cancel;
        this.confirm = confirm;
        this.dialogType = dialogType;
    }

    private void initView() {
        mTvTitle = findViewById (R.id.tv_dialog_title);
        mTvContent = findViewById (R.id.tv_dialog_content);
        mBtnCancel = findViewById (R.id.btn_dialog_cancel);
        mBtnCancel.setOnClickListener (this);
        mBtnConfirm = findViewById (R.id.btn_dialog_confirm);
        mBtnConfirm.setOnClickListener (this);
        mBtnConfirmCenter = findViewById (R.id.btn_dialog_confirm_center);
        mBtnConfirmCenter.setOnClickListener (this);
        if(dialogType == CONFIRM_DIALOG) {
            mBtnConfirmCenter.setVisibility (View.VISIBLE);
        } else if(dialogType == NOTICE_DIALOG) {
            mBtnConfirmCenter.setVisibility (View.INVISIBLE);
        }
    }

    private void initData() {
        mTvTitle.setText (title);
        mTvContent.setText (content);
        mBtnCancel.setText (cancel);
        mBtnConfirm.setText (confirm);
        mBtnConfirmCenter.setText (confirm);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId ()) {
            case R.id.btn_dialog_cancel:
                if(cancelClickListener != null) {
                    cancelClickListener.onCancelClick ();
                }
                break;
            case R.id.btn_dialog_confirm:
                if(confirmClickListener != null) {
                    confirmClickListener.onConfirmClick ();
                }
                break;
            case R.id.btn_dialog_confirm_center:
                cancel ();
                break;
            default:
                break;
        }
    }

    /**
     * 设置弹窗的显示内容
     *
     * @param title
     * @param content
     * @param cancel
     * @param confirm
     */
    public void setDialog(String title, String content, String cancel, String confirm, int dialogType) {
        this.title = title;
        this.content = content;
        this.cancel = cancel;
        this.confirm = confirm;
        this.dialogType = dialogType;
    }

    public static void showDialog(Context context,String title, String content, String cancel, String confirm, int dialogType){
        NoticeDialog dialog = new NoticeDialog (context,title,content,cancel,confirm,dialogType);
        dialog.show ();
    }
}

这个样式的弹窗支持自定义弹窗上面显示的文字和确定的样式,自定义Dialog的style代码:

<!--自定义Dialog-->
    <style name="CustomDialog" parent="android:style/Theme.Dialog">
        <!--背景颜色及和透明程度-->
        <item name="android:windowBackground">@android:color/transparent</item>
        <!--是否去除标题 -->
        <item name="android:windowNoTitle">true</item>
        <!--是否去除边框-->
        <item name="android:windowFrame">@null</item>
        <!--是否浮现在activity之上-->
        <item name="android:windowIsFloating">true</item>
        <!--是否模糊-->
        <item name="android:backgroundDimEnabled">true</item>
    </style>

使用起来也十分方便

if(dialog == null) {
                dialog = new NoticeDialog (context);
                dialog.setDialog ("提示信息", "您的账号在其他地方登录,若不是您本人操作,请及时修改密码", "取消", "登录", NoticeDialog.NOTICE_DIALOG);
                dialog.setOnConfirmClickListener (new NoticeDialog.OnConfirmClickListener () {
                    @Override
                    public void onConfirmClick() {
                        ActivityController.finishAll ();
                        MemoryData.getInstance ().getUserInterface ().startLoginActivity (context);
                        dialog.cancel ();
                    }
                });
                dialog.setOnCancelClickListener (new NoticeDialog.OnCancelClickListener () {
                    @Override
                    public void onCancelClick() {
                        ActivityController.finishAll ();
                        BackgroundService.getInstance ().stopService ();
                        dialog.cancel ();
                    }
                });
                dialog.setCanceledOnTouchOutside (false);
                dialog.show ();
            }

三、DialogFragment的使用


1.什么是DialogFragment?

DialogFragment在android 3.0时被引入。是一种特殊的Fragment,用于在Activity的内容之上展示一个模态的对话框。典型的用于:展示警告框,输入框,确认框等等。在DialogFragment产生之前,我们创建对话框一般采用AlertDialog和Dialog。注:官方不推荐直接使用Dialog创建对话框。

  • DialogFragment 本身是 Fragment 的子类,有着和 Fragment 基本一样的生命周期,使用 DialogFragment 来管理对话框,当旋转屏幕和按下后退键的时候可以更好的管理其生命周期
  • 在手机配置变化导致 Activity 需要重新创建时,例如旋转屏幕,基于 DialogFragment 的对话框将会由 FragmentManager 自动重建,然而基于 Dialog 实现的对话框却没有这样的能力

2.DialogFragment 的使用

使用 DialogFragment 至少需要实现 onCreateView() 或者 onCreateDialog() 方法,onCreateView() 即使用自定义的 xml 布局文件来展示 Dialog,而 onCreateDialog() 即使用 AlertDialog 或者 Dialog 创建出 我们想要的 Dialog。其生命周期为

  • onCreateDialog()->onActivityCreated()->onDestroyView()
public class MyDialogFragment extends DialogFragment {

    private static MyDialogFragment mMyDialog;

public static MyDialogFragment newInstance() {
        if(mMyDialog== null) {
            mMyDialog= new MyDialogFragment ();
        }
        return mMyDialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setCancelable (true);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog (getActivity (), R.style.PopupDialog);
        dialog.setCanceledOnTouchOutside (true);
        dialog.requestWindowFeature (Window.FEATURE_NO_TITLE);
        dialog.setContentView (R.layout.dialog_history_filter);
        Window window = dialog.getWindow ();
        WindowManager.LayoutParams params = window.getAttributes ();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.TOP;
        window.setAttributes (params);
        return dialog;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View dialogView = inflater.inflate (R.layout.dialog_history_filter, container, false);
        return dialogView;
    }

    @Override
    public void onStart() {
        super.onStart ();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView ();
        unbinder.unbind ();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss (dialog);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState (outState);
    }
}

在要显示的地方使用方法

MyDialogFragment myDialog = MyDialogFragment .newInstance();
myDialog .show (getFragmentManager (), MyDialogFragment .class.getName ());

四、悬浮框PopupWindow


使用

//准备PopupWindow的布局View
View popupView = LayoutInflater.from(this).inflate(R.layout.popup, null);
//初始化一个PopupWindow,width和height都是WRAP_CONTENT
PopupWindow popupWindow = new PopupWindow(
   ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//设置PopupWindow的视图内容
popupWindow.setContentView(popupView);
//点击空白区域PopupWindow消失,这里必须先设置setBackgroundDrawable,否则点击无反应
popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
popupWindow.setOutsideTouchable(true);
//设置PopupWindow动画
popupWindow.setAnimationStyle(R.style.AnimDown);
//设置是否允许PopupWindow的范围超过屏幕范围
popupWindow.setClippingEnabled(true);
//设置PopupWindow消失监听
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
    @Override
    public void onDismiss() {

    }
 });
//PopupWindow在targetView下方弹出
popupWindow.showAsDropDown(targetView);
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容