版权声明: https://blog.csdn.net/ShadowySpirits/article/details/80935028
原生 Dialog 的使用及不足
先贴出一般的使用方法:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("title")
.setMessage("message")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.create().show();
可以发现如果在项目中多次使用此种方法构建 Dialog 那么势必会产生大量重复的无用代码。且项目中如果需要多次展现相同的 Dialog ,这时每个 Dialog 都产生一个对象显然是极为浪费资源。再加上这个对象被回收还会带来的 ANR 风险。所以,我们需要对 Dialog 进行封装。
封装 Dialog 工具类的思路
即有如下需求:
- 丰富的自定义选项
- 尽量减小内存占用
其中第二点可以通过 Dialog 与页面的解耦来实现,具体的方式是建立一个单例模式的 DialogUtil ,用这个工具类来持有 Dialog 对象的弱引用,并提供展示、隐藏 Dialog 的方法给页面调用
这样做的好处是:
- 可以实现 Dialog 的复用
- 弱引用可以防止内存泄漏
- 统一管理 Dialog ,对象被回收时即使重建以避免 ANR
完成封装的示例 (showNormalDialog)
用 DialogType 来标记 Dialog
将你所使用的所有 Dialog 分别用常量(DialogType)标记,以便于区分不同的 Dialog。因为 Android 推荐使用注解替代枚举,所以这里用注解实现
添加示例:
@IntDef({CAR_CANCEL}) //在@IntDef注解中添加你的Dialog类型
@Retention(RetentionPolicy.SOURCE)
public @interface DialogType {
// 取消叫车
int CAR_CANCEL = 0; //定义你的Dialog类型,并写明注释
}
showNormalDialog 方法参数表
类型 | 传值 |
---|---|
Context | 当前Context |
@DialogType int | DialogType中定义的类型 |
int | Dialog标题的文字资源 |
int | Dialog右边按钮文字资源 |
int | Dialog左边按钮文字资源 |
CommonCallbackWithCancel | 两个按钮的回调接口 |
使用示例
DialogUtil.INSTANCE.showNormalDialog(
DialogType.CAR_CANCEL,
R.string.are_you_cancel_call,
R.string.action_confirm,
R.string.cancel,
new DialogUtil.CommonCallbackWithCancel() {
@Override public void onPositive() {
callCarCancel();
}
@Override public void onNegative() {
}
});