Android中“可恢复”listener的Dialog封装

BSSmartDialog设计说明

概述

Android应用开发中,如果需要弹出一个Dialog,Google SDK推荐的做法是使用DialogFragment作为容器。这样,在一些特殊操作情景下(Configuration Change,如旋转屏幕),开发者可以利用Fragment丰富的生命周期事件处理好Dialog的逻辑。我们知道,在发生Configuration Change时,Activity会销毁并立即重建。这样就带来一个问题,在Configuration Change之前设置给Dialog的listener对象,在Activity重建后是否还能够正常接收处理Dialog上的事件?

方案

Activity被重建时,所关联的DialogFragment也会跟着重建。由此得到启发:我们只要让新重建的DialogFragment所产生的事件,能够传到新重建的Host(即打开该DialogFragment的Activity或Fragment);也就是说,把Dialog的listener设置成该Host,那么listener的功能就不会受到Configuration Change的影响了。该BSSmartDialog尝试封装了这样的逻辑,它具备如下一些功能点:

  • 支持在Activity,或者Fragment上弹框
  • 支持指定一个任意布局layout,以Dialog的形式弹出
  • 可以设置在Activity重建的情况下,DialogFragment是否自动恢复(再次弹出)。默认为false,不弹出
  • 封装了AlertDialog,支持排队:在同一个Activity/Fragment上连续调用弹框时,前一个dismiss后,后一个才会show
  • 封装了AlertDialog,可以修改title,message,button的color、textsize属性

使用范例

  1. AlertDialog样式的使用

BSSmartDialogUtils
里提供了几个static调用方法。其中参数最多的方法如下:

BSSmartDialogUtils.showAlertDialog(Object activityOrFragment,
                                       CharSequence title,
                                       CharSequence message,
                                       CharSequence positiveButtonText,
                                       CharSequence negativeButtonText,
                                       CharSequence neutralButtonText,
                                       BSStyleParam styleParam,
                                       boolean autoRestore,
                                       DialogInterface.OnClickListener onClickListener,
                                       String tag)
  • 弹一个普通的类似“确定/取消”的对话框:可以按需选用参数较少的简单方法
  • 如果需要在页面重建时(Configuration Change)自动恢复弹框,设置autoRestore为true即可
  • 如果期望恢复弹框后,按钮的listener能重新连接上,则需设置onClickListener为该DialogFragment的Host(maybe
    Activity or Fragment)
  • 如果要修改默认title,message,button上的color,textsize样式,可以传入styleParam参数
  1. 一个任意布局的(水平居中)弹框(假设布局文件为abc)

BSSmartDialog smartDialog = BSSmartDialog.newInstance()
                .setLayoutId(R.layout.share_layout)
                .setDimAmount(0.3f)
                .setShowBottom(false)
                .setOnSmartDialogCreateListener(new BSSmartDialog.OnSmartDialogCreateListener() {
                    @Override
                    public void onSmartDialogCreate(BSViewHolder holder, BSSmartDialog dialog) {
                        Button button = holder.getView(R.id.action_button);
                        ...
                        BSSmartDialogUtils.dismiss(MainActivity.this, Tag_ShareDialog);
                    }
                });
        smartDialog.setAutoRestore(false).setTag(Tag_ShareDialog);
        smartDialog.show(getSupportFragmentManager());

最后希望对大家有所帮助,有问题欢迎讨论!
Github地址: https://github.com/chennyshan/BSSmartDialog

参考

NiceDialog: https://github.com/Othershe/NiceDialog

你可能感兴趣的:(Android中“可恢复”listener的Dialog封装)