《DialogFragment系列一之源码分析》
《DialogFragment系列二之Dialog封装》
《DialogFragment系列三之AlertDialog实现》
《DialogFragment系列四之StatusDialog(Progress、Success、Error)实现》
《DialogFragment系列五之常见问题》
上篇文章《DialogFragment系列一之源码分析》中分析了DialogFragment的优点并通过源码进行了说明,此篇要基于DialogFragment封装一个Dialog来初步替代原生Android中的Dialog,下面通过代码来展示:
public class Dialog extends AppCompatDialogFragment implements View.OnClickListener {
private DialogParams dialogParams;
public Dialog() {
this.dialogParams = new DialogParams();
}
protected void show(AppCompatActivity activity, String tag) {
if (!TextUtils.isEmpty(tag)) {
show(activity.getSupportFragmentManager(), tag);
} else {
show(activity);
}
}
protected void show(AppCompatActivity activity) {
show(activity.getSupportFragmentManager(), activity.getClass().getSimpleName());
}
@Nullable
@Override
public final View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//getDialog().setCancelable(setCancelable());
getDialog().setCanceledOnTouchOutside(setCancelable());
setCancelable(setCancelable());
//设置背景透明
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
return super.onCreateView(inflater, container, savedInstanceState);
}
protected boolean setCancelable() {
return dialogParams.isCancelable;
}
@NonNull
@Override
public final android.app.Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
View dialogLayout = LayoutInflater.from(getContext()).inflate(setLayoutRes(), null);
builder.setView(dialogLayout);
onViewCreated(dialogLayout, null);
return builder.create();
}
protected int setLayoutRes() {
return dialogParams.contentView;
}
@Override
public void onClick(View v) {
}
public class DialogParams {
AppCompatActivity activity;
int style;
int animations;
int contentView;
String tag;
boolean isCancelable;
}
public static class Builder {
private DialogParams P;
private Dialog dialog;
private Builder(AppCompatActivity activity) {
dialog = new Dialog();
P = dialog.dialogParams;
P.activity = activity;
}
public Builder setStyle(int val) {
P.style = val;
return this;
}
public Builder setAnimations(int val) {
P.animations = val;
return this;
}
public Builder setContentView(@LayoutRes int val) {
P.contentView = val;
return this;
}
public Builder setCancelable(boolean val) {
P.isCancelable = val;
return this;
}
public Dialog build() {
if (P.contentView == -1) {
throw new IllegalArgumentException("Please set setContentView");
}
dialog.show(P.activity, P.tag);
return dialog;
}
}
}
Dialog采用构造者模式,简化了DialogFragment的show()方法,封装了Dialog的实现,并预留了扩展性接口,开发者可以通过重写setLayoutRes()来实现不同布局,通过onViewCreated()来为布局控件赋值、设置监听等。
AlertDialog.png笔者基于Dialog实现了《Dialog全家桶》,先来看下部分实现效果:
具体实现请看
《DialogFragment系列三之AlertDialog实现》
《DialogFragment系列四之StatusDialog(Progress、Success、Error)实现》
读者有问或其他观点请留言交流,共同进步!
网友评论