当Android遇上设计模式之建造者(Builder)模式

时间:2024-10-08 09:43:52
public class AlertDialog2 { protected int mIcon; protected String mTitle; protected String mCancelText; protected String mConfirmText; protected Context mCtx; protected mClickListener; private View mContentView; private WindowManager mWindowManager; private View mRootView; public AlertDialog2(Context ctx) { this.mCtx = (); } public interface OnDialogClickListener { void onCancle(); void onConfirm(String content); } public void setIcon(int icon) { this.mIcon = icon; } public void setTitle(String title) { this.mTitle = title; } public void setContentView(View view) { this.mContentView = view; } public void setClickButton(String confirmText, String cancelText, listener) { this.mCancelText = cancelText; this.mConfirmText = confirmText; this.mClickListener = listener; } public void show() { // 使用WindowManager添加View到Window mWindowManager = (WindowManager) (Context.WINDOW_SERVICE); params = new (.MATCH_PARENT , .WRAP_CONTENT); = .FLAG_NOT_TOUCH_MODAL | .FLAG_NOT_FOCUSABLE; = .TYPE_PHONE; = 800; = 600; = ; mRootView = (mCtx).inflate(.layout_dialog, null); ImageView ivIcon = (ImageView) (.iv_dialog_icon); (mIcon); TextView tvTitle = (TextView) (.tv_dialog_title); (mTitle); LinearLayout contentLayout = (LinearLayout) (.llayout_content); (mContentView); Button btnCancel = (Button) (.btn_cancel); (mCancelText); (new () { @Override public void onClick(View v) { if (mClickListener != null) { (); } dismiss(); } }); Button btnConfirm = (Button) (.btn_confirm); (mConfirmText); (new () { @Override public void onClick(View v) { if (mContentView instanceof TextView) { if (mClickListener != null) { ((String) ((TextView) mContentView).getText()); } } dismiss(); } }); (mRootView, params); } public void dismiss() { if (mWindowManager != null) { (mRootView); } } /** * 建造者,AlertDialog内部类 * 此处采用链式调用 */ public static class Builder { private Context mCtx; private AlertDialog2 mDialog; public Builder(Context ctx) { this.mCtx = ctx; mDialog = new AlertDialog2(mCtx); } public Builder setIcon(int id) { (id); return this; } public Builder setTitle(String title) { (title); return this; } public Builder setMessage(String[] content) { if (content != null || > 0) { TextView tv = new TextView(mCtx); (content[0]); (16); (tv); } return this; } public Builder setOnDialogClickListener(String confirmText, String cancelText, listener) { (confirmText, cancelText, listener); return this; } public AlertDialog2 create() { return mDialog; } } }